From f38dc8aedc147c824b5eaa3621f399a623e9b681 Mon Sep 17 00:00:00 2001 From: feobay Date: Fri, 30 Aug 2024 16:19:40 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00188.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?IVGo=E7=89=88=E6=9C=AC=E7=A9=BA=E9=97=B4=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index def69277..0b1622ac 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -404,6 +404,47 @@ func max188(a, b int) int { } ``` +版本三:空间优化版本 + +```go +func maxProfit(k int, prices []int) int { + n := len(prices) + // k次交易,2 * k种状态 + // 状态从1开始计算,避免判断 + // 奇数时持有(保持或买入) + // 偶数时不持有(保持或卖出) + dp := make([][]int, 2) + dp[0] = make([]int, k * 2 + 1) + dp[1] = make([]int, k * 2 + 1) + + // 奇数状态时持有,i += 2 + for i := 1; i <= k * 2; i += 2 { + dp[0][i] = -prices[0] + } + + for i := 1; i < len(prices); i++ { + for j := 1; j <= k * 2; j++ { + if j % 2 == 1 { + dp[i % 2][j] = max(dp[(i - 1) % 2][j], dp[(i - 1) % 2][j - 1] - prices[i]) + } else { + dp[i % 2][j] = max(dp[(i - 1) % 2][j], dp[(i - 1) % 2][j - 1] + prices[i]) + } + } + } + + return dp[(n - 1) % 2][k * 2] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + + + ### JavaScript: ```javascript @@ -558,3 +599,4 @@ impl Solution { +