From e1e3b38eef494c4c7840264ea66a06802de4c1f9 Mon Sep 17 00:00:00 2001 From: Wen Date: Sat, 6 Nov 2021 20:29:00 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200309.=E6=9C=80=E4=BD=B3?= =?UTF-8?q?=E4=B9=B0=E5=8D=96=E8=82=A1=E7=A5=A8=E6=97=B6=E6=9C=BA=E5=90=AB?= =?UTF-8?q?=E5=86=B7=E5=86=BB=E6=9C=9F.md=20Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09.最佳买卖股票时机含冷冻期.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 59178c64..f5665a5e 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -208,6 +208,40 @@ class Solution: ``` Go: +```go +// 最佳买卖股票时机含冷冻期 动态规划 +// 时间复杂度O(n) 空间复杂度O(n) +func maxProfit(prices []int) int { + n := len(prices) + if n < 2 { + return 0 + } + + dp := make([][]int, n) + status := make([]int, n * 4) + for i := range dp { + dp[i] = status[:4] + status = status[4:] + } + dp[0][0] = -prices[0] + + for i := 1; i < n; i++ { + dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][1] - prices[i], dp[i - 1][3] - prices[i])) + dp[i][1] = max(dp[i - 1][1], dp[i - 1][3]) + dp[i][2] = dp[i - 1][0] + prices[i] + dp[i][3] = dp[i - 1][2] + } + + return max(dp[n - 1][1], max(dp[n - 1][2], dp[n - 1][3])) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` Javascript: