From bc77968c31186313bfd94627e09a49153aace468 Mon Sep 17 00:00:00 2001 From: Wen Date: Sat, 6 Nov 2021 20:21:23 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200188.=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?IV.md=20Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0188.买卖股票的最佳时机IV.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index bcb8a1ab..9e3ca112 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -275,6 +275,41 @@ class Solution: return dp[2*k] ``` Go: +版本一: +```go +// 买卖股票的最佳时机IV 动态规划 +// 时间复杂度O(kn) 空间复杂度O(kn) +func maxProfit(k int, prices []int) int { + if k == 0 || len(prices) == 0 { + return 0 + } + + dp := make([][]int, len(prices)) + status := make([]int, (2 * k + 1) * len(prices)) + for i := range dp { + dp[i] = status[:2 * k + 1] + status = status[2 * k + 1:] + } + for j := 1; j < 2 * k; j += 2 { + dp[0][j] = -prices[0] + } + + for i := 1; i < len(prices); i++ { + for j := 0; j < 2 * k; j += 2 { + dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i]) + dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i]) + } + } + return dp[len(prices) - 1][2 * k] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` Javascript: