From b91141ada6df34e1f1e4b6fb0e09ea31b1d64a3b Mon Sep 17 00:00:00 2001 From: Jerry-306 <82520819+Jerry-306@users.noreply.github.com> Date: Fri, 17 Sep 2021 11:07:10 +0800 Subject: [PATCH] =?UTF-8?q?0188=20=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAIV=20=20JavaScript=20=20?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92+?= =?UTF-8?q?=E7=A9=BA=E9=97=B4=E4=BC=98=E5=8C=96=20=20=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) 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]; +}; ``` -----------------------