diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index f0dff505..0dced9ef 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -251,6 +251,27 @@ func max(a, b int) int { } ``` +```go +// 动态规划 版本二 滚动数组 +func maxProfit(prices []int) int { + dp := [2][2]int{} // 注意这里只开辟了一个2 * 2大小的二维数组 + dp[0][0] = -prices[0] + dp[0][1] = 0 + for i := 1; i < len(prices); i++ { + dp[i%2][0] = max(dp[(i-1)%2][0], dp[(i - 1) % 2][1] - prices[i]) + dp[i%2][1] = max(dp[(i-1)%2][1], dp[(i-1)%2][0] + prices[i]) + } + return dp[(len(prices)-1)%2][1] +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} +``` + ### JavaScript: ```javascript