diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index bcb8a1ab..a166db72 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -280,6 +280,7 @@ Go: Javascript: ```javascript +// 方法一:动态规划 const maxProfit = (k,prices) => { if (prices == null || prices.length < 2 || k == 0) { return 0; @@ -300,6 +301,30 @@ const maxProfit = (k,prices) => { return dp[prices.length - 1][2 * k]; }; + +// 方法二:动态规划+空间优化 +var maxProfit = function(k, prices) { + let n = prices.length; + let dp = new Array(2*k+1).fill(0); + // dp 买入状态初始化 + for (let i = 1; i <= 2*k; i += 2) { + dp[i] = - prices[0]; + } + + for (let i = 1; i < n; i++) { + for (let j = 1; j < 2*k+1; j++) { + // j 为奇数:买入状态 + if (j % 2) { + dp[j] = Math.max(dp[j], dp[j-1] - prices[i]); + } else { + // j为偶数:卖出状态 + dp[j] = Math.max(dp[j], dp[j-1] + prices[i]); + } + } + } + + return dp[2*k]; +}; ``` -----------------------