美文网首页
122. Best Time to Buy and Sell S

122. Best Time to Buy and Sell S

作者: 乘瓠散人 | 来源:发表于2017-11-23 15:44 被阅读13次

最开始股票需要先买后卖

题解:

  1. suppose the first sequence is "a <= b <= c <= d", the profit is "d - a = (b - a) + (c - b) + (d - c)";
  2. suppose another one is "a <= b >= b' <= c <= d", the profit is not difficult to be figured out as "(b - a) + (d - b')";
    所以只需要考虑递增序列

AC代码:

public:
    int maxProfit(vector<int>& prices) {
        
        int sum =0;       
        for(int i=1; i<prices.size(); i++){
            if(prices[i] > prices[i-1]){
                sum += prices[i] - prices[i-1];
            }
        }
        
        return sum;
    }

RE代码:

public:
    int maxProfit(vector<int>& prices) {
        
        int sum =0;     
        for(int i=0; i<prices.size()-1; i++){
            if(prices[i] < prices[i+1]){
                sum += prices[i+1] - prices[i];
            }
        }
        
        return sum;
    }

相关文章

网友评论

      本文标题:122. Best Time to Buy and Sell S

      本文链接:https://www.haomeiwen.com/subject/zcmzvxtx.html