122. Best Time to Buy and Sell Stock II

最开始股票需要先买后卖

题解:

  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& prices) {
        
        int sum =0;       
        for(int i=1; i prices[i-1]){
                sum += prices[i] - prices[i-1];
            }
        }
        
        return sum;
    }

RE代码:

public:
    int maxProfit(vector& prices) {
        
        int sum =0;     
        for(int i=0; i

你可能感兴趣的:(122. Best Time to Buy and Sell Stock II)