309. Best Time to Buy and Sell Stock with Cooldown
之前写过这题https://blog.csdn.net/weixin_43462819/article/details/83271090
但是发现竟然没有把最重要的思想写出来,这里再写一次。
之前就是用普通的dp,这里尝试另一种思路:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if (sz < 2)
return 0;
vector<int> s0(sz, 0), s1(sz, 0), s2(sz, 0);
s0[0] = 0;
s1[0] = -prices[0];
s2[0] = 0;
for (int i = 1; i < sz; ++i) {
s0[i] = max(s0[i-1], s2[i-1]);
s1[i] = max(s1[i-1], s0[i-1]-prices[i]);
s2[i] = s1[i-1]+prices[i];
}
return max(s0[sz-1], s2[sz-1]);
}
};
s0是可以买的状态;
s1是可以卖的状态;
s2是冷却的状态。
然后因为都只用了前一个状态,可以优化内存:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sz = prices.size();
if (sz < 2)
return 0;
int canBuy = 0, canSell = -prices[0], rest = 0;
for (int i = 1; i < sz; ++i) {
int lastCanBuy = canBuy;
canBuy = max(canBuy, rest);
rest = canSell + prices[i];
canSell = max(canSell, lastCanBuy-prices[i]);
}
return max(rest, canBuy);
}