From a71f7d2127bae83cc42dffd20b4c460865006d15 Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Thu, 12 May 2022 23:23:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880123.=E4=B9=B0?= =?UTF-8?q?=E5=8D=96=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6?= =?UTF-8?q?=E6=9C=BAIII.md=EF=BC=89=EF=BC=9A=E5=A2=9E=E5=8A=A0typescript?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 56ade343..67c99497 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -352,6 +352,36 @@ const maxProfit = prices => { }; ``` +TypeScript: + +> 版本一 + +```typescript +function maxProfit(prices: number[]): number { + /** + dp[i][0]: 无操作; + dp[i][1]: 第一次买入; + dp[i][2]: 第一次卖出; + dp[i][3]: 第二次买入; + dp[i][4]: 第二次卖出; + */ + const length: number = prices.length; + if (length === 0) return 0; + const dp: number[][] = new Array(length).fill(0) + .map(_ => new Array(5).fill(0)); + dp[0][1] = -prices[0]; + dp[0][3] = -prices[0]; + for (let i = 1; i < length; i++) { + dp[i][0] = dp[i - 1][0]; + dp[i][1] = Math.max(dp[i - 1][1], -prices[i]); + dp[i][2] = Math.max(dp[i - 1][2], dp[i - 1][1] + prices[i]); + dp[i][3] = Math.max(dp[i - 1][3], dp[i - 1][2] - prices[i]); + dp[i][4] = Math.max(dp[i - 1][4], dp[i - 1][3] + prices[i]); + } + return Math.max(dp[length - 1][2], dp[length - 1][4]); +}; +``` + Go: > 版本一: