From 5483a714e7a3386467c50f49e7e543e04f51b3e5 Mon Sep 17 00:00:00 2001 From: Wen Date: Sat, 6 Nov 2021 20:17:16 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200123.=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?III.md=20Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 6a849c80..81f8e82d 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -317,7 +317,38 @@ const maxProfit = prices => { }; ``` +Go: +> 版本一: +```go +// 买卖股票的最佳时机III 动态规划 +// 时间复杂度O(n) 空间复杂度O(n) +func maxProfit(prices []int) int { + dp := make([][]int, len(prices)) + status := make([]int, len(prices) * 4) + for i := range dp { + dp[i] = status[:4] + status = status[4:] + } + dp[0][0], dp[0][2] = -prices[0], -prices[0] + + for i := 1; i < len(prices); i++ { + dp[i][0] = max(dp[i - 1][0], -prices[i]) + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]) + dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] - prices[i]) + dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] + prices[i]) + } + + return dp[len(prices) - 1][3] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` -----------------------