(M)Dynamic Programming:309. Best Time to Buy and Sell Stock with Cooldown
程序员文章站
2022-06-17 18:25:45
...
此题不会。看大神的分析:
对于这一天是否持股只有两种状态:持股状态(buy),没有持股状态(sell,cooldown)。
对于当天持股状态时,至当天的为止的最大利润有两种可能:1、今天没有买入,跟昨天持股状态一样;2、今天买入,昨天是冷却期,利润是前天卖出股票时候得到的利润减去今天股票的价钱。 二者取最大值。
对于当天未持股状态,至当天为止的最大利润有两种可能:1、今天没有卖出,跟昨天未持股状态一样;2、昨天持有股票,今天卖出了,利润是昨天持有股票时候的利润加上今天股票的价钱。 二者取最大值。
直至最后一天的状态应该是卖出状态。最终利润为sell[n-1];
状态转移方程:
sell[i] = max(sell[i-1], buy[i-1] + price[i]);
buy[i] = max(buy[i-1], sell[i-2] - price[i]);
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy(INT_MIN), sell(0), prev_sell(0), prev_buy;
for (int price : prices) {
prev_buy = buy;
buy = max(prev_sell - price, buy);
prev_sell = sell;
sell = max(prev_buy + price, sell);
}
return sell;
}
};
推荐阅读
-
309. Best Time to Buy and Sell Stock with Cooldown
-
Leetcode 309. Best Time to Buy and Sell Stock with Cooldown
-
[LeetCode] 309. Best Time to Buy and Sell Stock with Cooldown
-
【DP + 卖股票】LeetCode 309. Best Time to Buy and Sell Stock with Cooldown
-
LeetCode题解系列--309. Best Time to Buy and Sell Stock with Cooldown
-
动态规划-309. Best Time to Buy and Sell Stock with Cooldown
-
(M)Dynamic Programming:309. Best Time to Buy and Sell Stock with Cooldown
-
309. Best Time to Buy and Sell Stock with Cooldown
-
LeetCode 309. Best Time to Buy and Sell Stock with Cooldown
-
309. Best Time to Buy and Sell Stock with Cooldown