LeetCode#122 Best Time to Sell and Buy Stock II

1、初看时感觉很复杂,好像需要看之后很多天再择优。实际上画出折线图就能看到,这样做只是对最长区间取了一次计算,当股票一直上升时当然是最优解,但一旦中间出现下跌,就少算了上涨的这一段。
简单来说,低买高卖一定没错。
那么为什么?
2、这里是一个推导:为什么这样最优

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int duration = prices.size();

        // if(duration < 2)
        //     return 0;
        int profits = 0;
        for(int i = 1; i < duration; i++){
            if(prices[i] > prices[i-1])
                profits += (prices[i] - prices[i-1]);
        }

        return profits;
    }
};

猜你喜欢

转载自blog.csdn.net/rpybd/article/details/81710249