码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock II

时间:2014-10-19 00:05:52      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:blog   io   java   for   2014   on   log   new   as   

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

标签:blog   io   java   for   2014   on   log   new   as   

原文地址:http://blog.csdn.net/tspatial_thunder/article/details/40227577

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!