LeetCode 122. 买卖股票的最佳时机 II

class Solution {
    //对于 [a, b, c, d],如果有 a <= b <= c <= d ,那么最大收益为 d - a。而 d - a = (d - c) + (c - b) + (b - a) ,
    //因此当访问到一个 prices[i] 且 prices[i] - prices[i-1] > 0,那么就把 prices[i] - prices[i-1] 添加到收益中。
    public int maxProfit(int[] prices) {
        int profit = 0;
        for(int i = 1;i < prices.length;i++){
            int tmp = prices[i] - prices[i - 1];
            if(tmp > 0){
                profit += tmp;
            }
        }
        return profit;
    }
}

 

posted @ 2020-11-02 16:59  peanut_zh  阅读(49)  评论(0编辑  收藏  举报