新增 0122.买卖股票的最佳时机II(动态规划).md Go解法

This commit is contained in:
Wen
2021-11-06 20:14:43 +08:00
parent 9b79393763
commit 36a4a90992

View File

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