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 +} +``` -----------------------