mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
122.买卖股票的最佳时机II增加Go动态规划滚动数组版本
This commit is contained in:
@ -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
|
||||
|
Reference in New Issue
Block a user