现在的位置: 首页 > 综合 > 正文

Best Time to Buy and Sell Stock II

2018年03月18日 ⁄ 综合 ⁄ 共 283字 ⁄ 字号 评论关闭

明白了上一题是求最大的连续子数组之和后,这题就更加简单了,遇到小于0的就不要加。

public class Solution {
    public int maxProfit(int[] prices) {
    	
    	if(prices.length < 2)
    		return 0;
        
    	int n = prices.length;
    	int[] diffs = new int[n];
        
        for(int i=0;i<n-1;i++)
        	diffs[i] = prices[i+1] - prices[i];
        
        int sum = 0;
        
        for(int i=0;i<n-1;i++)
        {
        	if(diffs[i]>0)
        		sum+=diffs[i];
        }
        
        return sum;
    }
}

抱歉!评论已关闭.