首页 > 代码库 > Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II

明确了上一题是求最大的连续子数组之和后。这题就更加简单了,遇到小于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;
    }
}


Best Time to Buy and Sell Stock II