From afbcb1d98bd5a0e40f9f65d1ced60e62c286fbf2 Mon Sep 17 00:00:00 2001 From: XZY <1214807740@qq.com> Date: Mon, 15 Jul 2024 12:14:43 +0800 Subject: [PATCH 1/2] =?UTF-8?q?Update=20121.=20=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=BA.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 22 +++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index e9aea0e6..df586ff9 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -466,7 +466,7 @@ function maxProfit(prices: number[]): number { }; ``` -> 动态规划 +> 动态规划:版本一 ```typescript function maxProfit(prices: number[]): number { @@ -487,6 +487,26 @@ function maxProfit(prices: number[]): number { }; ``` +> 动态规划:版本二 + +```typescript +// dp[i][0] 表示第i天持有股票所得最多现金 +// dp[i][1] 表示第i天不持有股票所得最多现金 +function maxProfit(prices: number[]): number { + const dp:number[][] = Array(2).fill(0).map(item => Array(2)); + dp[0][0] = -prices[0]; + dp[0][1] = 0; + + for (let i = 1; i < prices.length; i++) { + dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], -prices[i]); + dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]); + } + + // 返回不持有股票的最大现金 + return dp[(prices.length-1) % 2][1]; +}; +``` + ### C#: > 贪心法 From 06a089e780e1be6206e58ed052b6615ee0cb7dc2 Mon Sep 17 00:00:00 2001 From: Jack Lin Date: Mon, 15 Jul 2024 15:25:31 +0800 Subject: [PATCH 2/2] =?UTF-8?q?0406.=E6=A0=B9=E6=8D=AE=E8=BA=AB=E9=AB=98?= =?UTF-8?q?=E9=87=8D=E5=BB=BA=E9=98=9F=E5=88=97.md:=20Fix=20typo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0406.根据身高重建队列.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/problems/0406.根据身高重建队列.md b/problems/0406.根据身高重建队列.md index b7e94543..d92a7f3f 100644 --- a/problems/0406.根据身高重建队列.md +++ b/problems/0406.根据身高重建队列.md @@ -87,7 +87,7 @@ 回归本题,整个插入过程如下: 排序完的people: -[[7,0], [7,1], [6,1], [5,0], [5,2],[4,4]] +[[7,0], [7,1], [6,1], [5,0], [5,2], [4,4]] 插入的过程: * 插入[7,0]:[[7,0]]