309. Best Time to Buy and Sell Stock with Cooldown

题目:Best Time to Buy and Sell Stock with Cooldown

原题链接:https://leetcode.com/problems/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]

给出一组整数序列,位置 i 上的元素是第 i 天的股票价格,设计一个算法来获得最大的收益。你可以进行多次交易,不过有下面两个限制:
1. 一天只能进行一种交易,并且你必须要先把股票全部卖出去,才能买;
2. 当前一天卖掉股票之后,在第二天必须休息(cooldown)。
例:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
即 -1(买) + 2(卖) + 0(休息) - 0(买) + 2(卖) = 3。

需要用动态规划来做,令buy[ i ]表示在第 i 天或之前以buy结尾所获得的最大收益,sell[ i ]表示在第 i 天或之前以sell结尾的最大收益,rest[ i ]表示在第 i 天或之前以cooldown结尾的最大收益。
那么,
buy[ i ] = max ( rest[ i - 1] - price, buy[i - 1]);
在第 i 天以buy结尾的话,那么前一天势必是rest,所以buy[ i ]有可能是rest[ i - 1] - price,如果第 i 天不是buy结尾的话,那么buy[ i ]就继承buy[ i - 1]的值,最终buy[ i ]的值取两者的较大值。
sell[ i ] = max (buy[i - 1] + price, sell[i - 1]);
如果第 i 天以sell结尾,那么第i - 1天势必为buy, 所以sell[ i ]有可能是buy[ i - 1] + price,如果第 i 天不是buy结尾的话,那么sell[ i ]就继承sell[ i - 1]的值,最终sell[ i ]的值去两者的较大值。
rest[ i ] = max ( sell[ i - 1], buy[ i - 1], rest[i - 1] );
由于任何时候都可以rest,那么rest[ i ]的值可以是前一天各种可能状态的值的延续,所以rest[ i ]取他们的最大值。不过考虑到实际情况,在当天之前以sell结尾的最大收益肯定会保证不小于以buy或者rest结尾的,所以实际上rest[ i ]是等于 sell[ i - 1]的。
这样我们可以把rest[ i ]给简化成sell[ i - 1],那么
buy[ i ] = max(sell[ i - 2 ] - price, buy[ i - 1]);
sell[ i ] = max(buy[ i - 1] + price, sell[ i - 1 ]);
这样我们只需要知道sell[ i - 2], sell[ i - 1], buy[i - 1],就可以不断的更新状态了。
我们可以设置一个sell表示sell[ i ], preSell表示sell[ i ], buy表示buy[ i ], preBuy表示buy[ i - 1 ],初试状态假设一个第0天的状态(buy = INT_MIN, sell = 0, preSell = 0),这样相对于从prices序列开始就是它前一天的状态。
那么每次扫描到当天的价格num,则:
preBuy = buy;
buy = max(preSell - num, preBuy);
preSell = sell;
sell = max(preSell, preBuy + num);
一直重复到数组扫描结束,sell中的数值就是最大的收益。

代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy = INT_MIN, sell = 0, preSell = 0, preBuy;
        for (int num : prices) {
            preBuy = buy;
            buy = max(preSell - num, preBuy);
            preSell = sell;
            sell = max(preSell, preBuy + num);
        }
        return sell;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值