[LeetCode]Best Time to Buy and Sell Stock

来源:互联网 发布:网络蔬菜超市 编辑:程序博客网 时间:2024/06/13 20:20

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

121Best Time to Buy and Sell Stock40.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
原创粉丝点击