From 0846cd122e93e2472976164484d971990bd68ffa Mon Sep 17 00:00:00 2001 From: feobay Date: Fri, 30 Aug 2024 16:05:11 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00309.=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=9FGo=E7=89=88=E6=9C=AC=E4=B8=80?= =?UTF-8?q?=E7=BB=B4=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...09.最佳买卖股票时机含冷冻期.md | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/problems/0309.最佳买卖股票时机含冷冻期.md b/problems/0309.最佳买卖股票时机含冷冻期.md index 95689a48..4913b8bd 100644 --- a/problems/0309.最佳买卖股票时机含冷冻期.md +++ b/problems/0309.最佳买卖股票时机含冷冻期.md @@ -357,6 +357,42 @@ func max(a, b int) int { } ``` +```go +// 一维优化版本 +// 时间复杂度O(n), 空间复杂度O(1) +func maxProfit(prices []int) int { + + // 0: 持有,一直持有和买入 + // 1: 不持有,一直不持有(不包含前一天卖出,因为这样的一天是冷静期,状态有区别) + // 2:不持有,今天卖出 + // 3:冷静期,前一天卖出(一直不持有) + dp0, dp1, dp2, dp3 := -prices[0], 0, 0, 0 + + n := len(prices) + + for i := 1; i < n; i++ { + t0 := max(dp0, max(dp1, dp3)-prices[i]) + t1 := max(dp1, dp3) + t2 := dp0 + prices[i] + t3 := dp2 + + // 更新 + dp0, dp1, dp2, dp3 = t0, t1, t2, t3 + } + + return max(dp1, max(dp2, dp3)) +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` + + + ### Javascript: > 不同的状态定义 感觉更容易理解些 @@ -540,3 +576,4 @@ impl Solution { +