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

[Leetcode]Best Time to Buy and Sell Stock II

时间:2015-10-28 01:32:51      阅读:128      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!