Merge pull request #2786 from markwang1992/122-maxProfit

122.买卖股票的最佳时机II增加Go动态规划滚动数组版本
This commit is contained in:
程序员Carl
2024-11-11 10:05:56 +08:00
committed by GitHub

View File

@ -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