LeetCode题解:309. 最佳买卖股票时机含冷冻期,动态规划,JavaScript,详细注释
chencl1986 opened this issue · comments
Lee Chen commented
原题链接:309. 最佳买卖股票时机含冷冻期
解题思路:
-
一共交易
(prices.length
天,因此可以创建同样长度的dp
数组递推,每天有买卖两种状态,dp[i][0]为买,dp[i][1]为卖。 -
第
i
天可以做两种操作:- 由于买入需要和上一次卖出间隔一天,因此只能在
i - 2
天已卖出的基础上买入,表示为dp[i - 2][1] - prices[i]
。同时第i
天的买入状态,是0
到i
天的最优解,因此买入的状态转移方程为dp[i][0] = Math.max(dp[i - 1][0], dp[i - 2][1] - prices[i]);
。 - 卖出无需间隔,因此可以在
i - 1
天买入的基础上卖出,表示为dp[i - 1][0] + prices[i]
。同时第i
天的卖出状态,是0
到i
天的最优解,因此卖出的状态转移方程为dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
。
- 由于买入需要和上一次卖出间隔一天,因此只能在
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
// 共有prices.length天的状态,创建相应长度的数组递推
// 每天可以做买卖两种操作,dp[i][0]为买,dp[i][1]为卖
let dp = new Array(prices.length);
// 由于卖了之后,有1天的冷冻期才能再购买,因此要向前递推2天,必须提前创建2天的状态
// 第0天只能买不能卖
dp[0] = [-prices[0], 0];
// 第1天可以买或卖
dp[1] = [
// 第0天和第1天都买的最佳状态
Math.max(-prices[0], -prices[1]),
// 第0天买,然后第1天卖,以及两天都不卖的最佳状态
Math.max(0, prices[1] - prices[0]),
];
// 考虑到冷冻期,需要从第2天开始递推
for (let i = 2; i < prices.length; i++) {
dp[i] = [
// 递推第i天的买入的状态
Math.max(
dp[i - 1][0], // 0~i-1天买入的状态
dp[i - 2][1] - prices[i], // i-2天卖出,第i天买入的状态
),
// 递推第i天的卖出的状态
Math.max(
dp[i - 1][1], // 0~i-1天卖出的状态
dp[i - 1][0] + prices[i], // i-1天买入,第i天卖出的状态
),
];
}
// 最后一天的卖出状态,就是总利润
return dp[dp.length - 1][1] || 0;
};