[Leetcode] Best Time to Buy and Sell Stock I | III

题目一:在一段时间内通过一次购买售出使收益最大

这属于动态规划的问题,状态方程是

profile[i]=profile[i-1] + price[i]      (profile[i-1] >0)

profile[i]=price[i]          (profile[i-1] <=0)

在所有profile[i]中找到最大的即可。


题目二:在一段时间内通过两次购买和抛售获得最大的收益。

转换一下就是找到一个点 i,使max[i]=profile[0-i] +profile[i+1-end] 最大,这两个其实就是上面的问题算两次,将 0-end的所有i遍历,最后只要求max[i]中最大的即可。


int maxProfit(vector<int> &prices)	
{
	if(prices.size()<1)  return 0;
	int *maxprice1=new int[prices.size()];
	int *maxprice2=new int[prices.size()];
	for(int i=0; i< prices.size(); i++) maxprice1[i]=0;
	for(int i=0; i< prices.size(); i++) maxprice2[i]=0;

	int tmp=0 ,i=0;

	int increase=0;

	for(i=1; i< prices.size(); i++)				//从price[0..i]推出price[0..i+1]
	{
		tmp=prices[i]-prices[i-1];
		if(increase>0)
			increase= increase + tmp;
		else 
			increase= tmp;				//保存从 0 到i 能得到的最大收益

		maxprice1[i]=max(maxprice1[i-1] ,increase);     //动规,前 i个点 出现的最大收益
	}

	increase=0;
	for(i= prices.size()-1 ; i> 1; i--)			//从price[i..n]推出price[i-1..n]的最大profit
	{
		tmp=prices[i]-prices[i-1];
		if(increase>0)
			increase= increase + tmp;
		else 
			increase= tmp;				//保存从 0 到i 能得到的最大收益

		maxprice2[i-1]=max(maxprice2[i] ,increase);     //动规,前 i个点 出现的最大收益
	}
	increase=0;
	for(i=1; i< prices.size(); i++)
		increase=max(increase,maxprice1[i]+maxprice2[i] );

	delete []maxprice1;
	delete []maxprice2;

	return increase;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值