diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 2dc1e874..bb8909cd 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -284,6 +284,24 @@ const maxProfit = (prices) => { }; ``` +```javascript +// 一维数组空间优化 +const maxProfit = (prices) => { + const n = prices.length + const dp = new Array(4).fill(0) + dp[0] = -prices[0] + for (let i = 1; i < n; i ++) { + const temp = dp[0] // 缓存上一次的状态 + const temp1 = dp[2] + dp[0] = Math.max(dp[0], Math.max(dp[3] - prices[i], dp[1] - prices[i])) // 持有状态 + dp[1] = Math.max(dp[1], dp[3]) // 今天不操作且不持有股票 + dp[2] = temp + prices[i] // 今天卖出股票 + dp[3] = temp1 // 冷冻期 + } + return Math.max(...dp) +}; +``` + -----------------------