From 65531e6de8da4ed86347dc6b6980e9df0808d909 Mon Sep 17 00:00:00 2001 From: Jerry-306 <82520819+Jerry-306@users.noreply.github.com> Date: Fri, 17 Sep 2021 10:11:52 +0800 Subject: [PATCH] =?UTF-8?q?0122=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=BA=E2=85=B1=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=20js=20=E7=89=88=E6=9C=AC=20=E6=BB=9A=E5=8A=A8?= =?UTF-8?q?=E6=95=B0=E7=BB=84=20=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...股票的最佳时机II(动态规划).md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 5dfe3f0e..c324d392 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -202,6 +202,7 @@ Go: Javascript: ```javascript +// 方法一:动态规划(dp 数组) const maxProfit = (prices) => { let dp = Array.from(Array(prices.length), () => Array(2).fill(0)); // dp[i][0] 表示第i天持有股票所得现金。 @@ -222,6 +223,21 @@ const maxProfit = (prices) => { return dp[prices.length -1][0]; }; + +// 方法二:动态规划(滚动数组) +const maxProfit = (prices) => { + // 滚动数组 + // have: 第i天持有股票最大收益; notHave: 第i天不持有股票最大收益 + let n = prices.length, + have = -prices[0], + notHave = 0; + for (let i = 1; i < n; i++) { + have = Math.max(have, notHave - prices[i]); + notHave = Math.max(notHave, have + prices[i]); + } + // 最终手里不持有股票才能保证收益最大化 + return notHave; +} ```