首页 > 其他 > 详细

[Leetcode]Best Time to Buy and Sell Stock II

时间:2015-10-28 01:31:10      阅读:214      评论:0      收藏:0      [点我收藏+]
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        if(n<=1) return 0;
        if(n==2) return prices[1]>prices[0] ? prices[1] - prices[0] : 0;
        int profit = 0;
        int begin = 0;
        int end = 0;
        for(int i = 0;i<n-1;++i) {
            while(prices[i]>=prices[i+1] ) {
                i++;
                if(i==n-1) return profit;
                if(i== n-2) {
                    if(prices[i] >= prices[i+1])
                        return profit;
                    else {
                        profit += prices[i+1] -prices[i];
                        return profit;
                    }
                }
            }
            begin = i;
            while(i!=n-1 && prices[i]<prices[i+1]) i++;
            end = i;
            profit +=prices[end] - prices[begin];
        }
        return profit;
  注意边角情况。
int maxProfit(vector<int> &prices) {
    int ret = 0;
    for (size_t p = 1; p < prices.size(); ++p) 
      ret += max(prices[p] - prices[p - 1], 0);    
    return ret;
}

  最优解答,感觉自己好渣。

只要有增加就可以加到总和里面。。。不需要计算上涨的区间。。

还是要仔细分析问题啊。

[Leetcode]Best Time to Buy and Sell Stock II

原文:http://www.cnblogs.com/shenbingyu/p/4916077.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!