From 55239579183ffebf29c7cfae52c626b996676061 Mon Sep 17 00:00:00 2001 From: markwang Date: Sat, 12 Oct 2024 10:10:05 +0800 Subject: [PATCH] =?UTF-8?q?122.=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8?= =?UTF-8?q?=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BAII=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0Go=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E6=BB=9A?= =?UTF-8?q?=E5=8A=A8=E6=95=B0=E7=BB=84=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...票的最佳时机II(动态规划).md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index f0dff505..0dced9ef 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -251,6 +251,27 @@ func max(a, b int) int { } ``` +```go +// 动态规划 版本二 滚动数组 +func maxProfit(prices []int) int { + dp := [2][2]int{} // 注意这里只开辟了一个2 * 2大小的二维数组 + dp[0][0] = -prices[0] + dp[0][1] = 0 + for i := 1; i < len(prices); i++ { + dp[i%2][0] = max(dp[(i-1)%2][0], dp[(i - 1) % 2][1] - prices[i]) + dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0] + prices[i]) + } + return dp[(len(prices)-1)%2][1] +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + ### JavaScript: ```javascript