From 495998e509527b53a8b84cc0527dfcff4fc1e1af Mon Sep 17 00:00:00 2001 From: Steve2020 <841532108@qq.com> Date: Fri, 13 May 2022 12:07:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=EF=BC=880188.=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=BAIV.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 --- .../0188.买卖股票的最佳时机IV.md | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 61c558a1..27eb38c3 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -409,5 +409,27 @@ var maxProfit = function(k, prices) { }; ``` +TypeScript: + +```typescript +function maxProfit(k: number, prices: number[]): number { + const length: number = prices.length; + if (length === 0) return 0; + const dp: number[][] = new Array(length).fill(0) + .map(_ => new Array(k * 2 + 1).fill(0)); + for (let i = 1; i <= k; i++) { + dp[0][i * 2 - 1] = -prices[0]; + } + for (let i = 1; i < length; i++) { + for (let j = 1; j < 2 * k + 1; j++) { + dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + Math.pow(-1, j) * prices[i]); + } + } + return dp[length - 1][2 * k]; +}; +``` + + + -----------------------