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

其实只需要大于0的买卖,都加入max中,就是最大的交易.

class Solution {
    public int maxProfit(int[] prices) {
        int i;
        int max = 0;
        if(prices == null)
        {
            return 0;
        }
        else
        {
            for(i = 0;i <= prices.length-2;i++)
            {
                if(prices[i+1] - prices[i] > 0)
                {
                    max = prices[i+1] - prices[i] + max;
                }
            }
        }
        return max;
    }
}

最关键就是为何可以直接前后两个进行判断,不用跨数字。

比如:[7,1,5,1,3,6,4],该最大的为9,就是5-1和6-1,后者就跨数字了,但是,看到其中3-1是大于0加到了max中,6-3也大于0加到了max中,

那么,相当于6-1就已经分两段加入了,不担心缺值。

原文地址:https://www.cnblogs.com/wzwi/p/10825202.html