diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 5dfe3f0e..5a39c8b1 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -199,6 +199,33 @@ class Solution: ``` Go: +```go +// 买卖股票的最佳时机Ⅱ 动态规划 +// 时间复杂度O(n) 空间复杂度O(n) +func maxProfit(prices []int) int { + dp := make([][]int, len(prices)) + status := make([]int, len(prices) * 2) + for i := range dp { + dp[i] = status[:2] + status = status[2:] + } + dp[0][0] = -prices[0] + + for i := 1; i < len(prices); i++ { + dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i]) + dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]) + } + + return dp[len(prices) - 1][1] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +``` Javascript: ```javascript