From 4164ddbb69da491b05f201a39b7b4c6233fad929 Mon Sep 17 00:00:00 2001 From: fw_qaq Date: Fri, 10 Mar 2023 11:11:54 +0800 Subject: [PATCH] =?UTF-8?q?Update=200122.=E4=B9=B0=E5=8D=96=E8=82=A1?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAII.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0122.买卖股票的最佳时机II.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index d094da48..a863afe7 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -274,6 +274,7 @@ const maxProfit = (prices) => { ### TypeScript: +贪心 ```typescript function maxProfit(prices: number[]): number { let resProfit: number = 0; @@ -284,6 +285,21 @@ function maxProfit(prices: number[]): number { }; ``` +动态规划 +```typescript +function maxProfit(prices: number[]): number { + const dp = Array(prices.length) + .fill(0) + .map(() => Array(2).fill(0)) + dp[0][0] = -prices[0] + for (let i = 1; i < prices.length; i++) { + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] - prices[i]) + dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]) + } + return dp[prices.length - 1][1] +} +``` + ### Rust 贪心: