首页 > 其他 > 详细

Best Time to Buy and Sell Stock II

时间:2014-03-17 17:04:23      阅读:485      评论:0      收藏:0      [点我收藏+]

题目原型:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

基本思路:

在题1的基础上,这个题是说可以交易多次。所以我们在保证即将减的情况下卖出,即将升的情况下买入。

	public int maxProfit(int[] prices)
	{
		if(prices==null||prices.length==0)
			return 0;
		int maxProfit = 0;
		int count = 0;
		
		for(int i = prices.length-1;i>0;i--)
		{
			if(count>=0)
			{
				if(count<=count+(prices[i]-prices[i-1]))
					count+=(prices[i]-prices[i-1]);
				else
				{
					maxProfit+=count;//卖出
					count = 0;
				}
			}
			else
			{
				count = (prices[i]-prices[i-1])>0?(prices[i]-prices[i-1]):0;
			}
		}
		if(count>0)
			maxProfit+=count;
		return maxProfit;
	}


 

 

Best Time to Buy and Sell Stock II,布布扣,bubuko.com

Best Time to Buy and Sell Stock II

原文:http://blog.csdn.net/cow__sky/article/details/21373523

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