首页 > 其他 > 详细

[LeetCode]Best Time to Buy and Sell Stock II

时间:2016-01-22 17:40:58      阅读:174      评论:0      收藏:0      [点我收藏+]

题目:给定一个整形数组,表示股票走势,股票能够买入卖出随意次。求能够攒到的最大利润

算法:相当于对股票上升走势求和

比如:股票走势:1,1,3,2,5,7,1,3,2,0。则最大利润为(3-1)+(5-2)+(7-5)+(3-1)=9

技术分享技术分享

public class Solution {
    public int maxProfit(int[] prices) {
	    	if (0 == prices.length) {
	    		// Empty array
	    		return 0;
	    	}
	    	
	        int maxProfile = 0;
	        int sellIn = prices[0];
	        for (int i=1; i<prices.length; ++i) {
	        	if (prices[i] > sellIn) {
	        		maxProfile += (prices[i]-sellIn);
	        		sellIn = prices[i];
	        	} else {
	        		sellIn = prices[i];
	        	}
	        }
	        return maxProfile;
	    }
}


[LeetCode]Best Time to Buy and Sell Stock II

原文:http://www.cnblogs.com/bhlsheji/p/5151283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!