From 78c1d0209fc1bfcba73d52294b4b11db09f27f8a Mon Sep 17 00:00:00 2001 From: Jack <965555169@qq.com> Date: Thu, 5 Aug 2021 12:31:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0121.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?-JavaScript=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 259fff34..8ad6c8c6 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -313,6 +313,26 @@ func max(a,b int)int { } ``` +JavaScript: + +```javascript +const maxProfit = prices => { + const len = prices.length; + // 创建dp数组 + const dp = new Array(len).fill([0, 0]); + // dp数组初始化 + dp[0] = [-prices[0], 0]; + for (let i = 1; i < len; i++) { + // 更新dp[i] + dp[i] = [ + Math.max(dp[i - 1][0], -prices[i]), + Math.max(dp[i - 1][1], prices[i] + dp[i - 1][0]), + ]; + } + return dp[len - 1][1]; +}; +``` +