您的位置:首页 > 其它

[LeetCode 309] Best Time to Buy and Sell Stock with Cooldown(动态规划及进一步优化)

2016-11-24 19:29 417 查看

题目内容

309 Best Time to Buy and Sell Stock with Cooldown

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) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]

maxProfit = 3

transactions = [buy, sell, cooldown, buy, sell]

Credits:

Special thanks to @dietpepsi for adding this problem and creating all test cases.

题目来源

题目简述

买卖股票以获得最大利益,一天只能进行一次操作,不能同时进行多笔交易,卖出后一天不能再买。

题目分析

根据之前做过的同类型题目([LeetCode 121]Best Time to Buy and Sell Stock(动态规划) ),应使用记录数据的动态规划方法。

用buy[i],sell[i],rest[i]表示第i天进行相应操作后利润最大值。显然,可列出状态转移方程为

buy[i]=max(buy[i-1],rest[i-1]-prices[i])

sell[i]=max(sell[i-1],buy[i-1]+prices[i])

rest[i]=max(sell[i-1],cool[i-1],buy[i-1])

由第一式可推出buy[i]<rest[i]。由第二式可推出sell[i]>=rest[i]。所以第三式可化为rest[i]=sell[i-1]。显然第一式中rest[i-1]=sell[i-2]。

简化之后的状态转移方程为

buy[i]=max(buy[i-1],sell[i-2]-prices[i])

sell[i]=max(sell[i-1],buy[i-1]+prices[i])

即成为典型的动态规划问题,代码与上题类似。

此时空间复杂度为O(n)。观察上述方程并注意变量以适当地顺序进行赋值,可以将空间复杂度降低到O(1)。具体代码如下。

代码示例

class Solution {
public:
int maxProfit(vector<int>& prices) {
int len=prices.size();
int buy=INT_MIN;
int pre_buy=0;
int pre_sell=0;
int sell=0;
for(int i=0;i!=len;i++)
{
pre_buy=buy;
buy=max(pre_sell-prices[i],buy);
pre_sell=sell;
sell=max(pre_buy+prices[i],sell);

}
return sell;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: