码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode------Best Time to Buy and Sell Stock II

时间:2015-02-02 12:28:59      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:

标题: Best Time to Buy and Sell Stock II
通过率: 37.3%
难度: 中等

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

我感觉这道题目还是没有描述清楚,与第一个版本相似,这道题可以多次购买和卖出求最大值,刚开始我以为是手里可以购买两次然后再卖,那么本题就是每次求一个正序的最大最小,但是我发现手里不能同时持有多张股票,也就是说如果购买了一次。那么下一手只能是卖出了。这个题目就变成了贪心算法的题目。只要下一次比当前这一次价格高,那么就买入,然后下一次卖出,那么利润公式就是 result+=prices[i+1]-prices[i];

这个题目还有一个第三版本,但是是hard难度。我暂时不考虑,hard难度应该是用动态规划了。

一次遍历结果就出来了,直接看代码:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if(prices.length<=1)return 0;
 4         int result=0;
 5         for(int i=0;i<prices.length-1;i++){
 6             if(prices[i+1]>prices[i]){
 7                 result=result+prices[i+1]-prices[i];
 8             }
 9         }
10         return result;
11     }
12 }

 

leetcode------Best Time to Buy and Sell Stock II

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4267223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!