[LeetCode]Best Time to Buy and Sell Stock

今天写的题目是Best Time to Buy and Sell Stock,之前写过它的II版本,但是是用贪婪算法,这次写的是用动态规划

121 Best Time to Buy and Sell Stock 40.4% Easy
题目要求是这样的:

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

输入是一个数组,里面的值代表第i天stock能买入/卖出的价格,你只能买入并卖出一次,并且只能先买入后再卖出,要求的是什么时候买入卖出能得到最大收益。

题目看似很简单,但是我们并不知道我们在买入时是否之后存在价格更低的时候可以买入获得更大收益,如果有,又不能保证在之后有更好的卖出价使得收益比原来的选择更好。因此我们需要动态规划。当我们找到第一个 prices[i]<prices[i+1] 时,假设我们买入,当然只是假设,并不是最终确定的买入的时间,之后只要存在prices[i]>prices[buy],那么我们计算差价,取最大值作为最终收益。当然,如果之后出现更低的买入价,我们再假设此时为新的买入时间buy_2,如果出现了prices[i]-prices[buy]>profit,自然也有prices[i]-prices[buy_2]>profit,此时差价就是新的收益了,如果一直没有prices[i]-prices[buy_2]>profit,那么说明没有合适的卖出时间使得收益更高,原来的profit就是最大收益。

代码如下:

int maxProfit(vector<int>& prices) {
	if(prices.size()==0)
	{
	    return 0;
	}
	
	int profit=0;
	int buy=0;
	int sell=0;
	for(int i=0;i<prices.size()-1;i++)
	{
	    if(prices[i]<prices[i+1])
	    {
	        profit=prices[i+1]-prices[i];
	        buy=i;
	        break;
	    }
	}
	int j=buy+1;
	while(j<prices.size())
	{
	    if(profit<prices[j]-prices[buy])
	    {
	        profit=prices[j]-prices[buy];
	    }
	    if(prices[j]<prices[buy])
	    {
	        buy=j;
	    }
	    
	    j++;
	}
	
	return profit;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值