Merge pull request #896 from RyouMon/master

新增最佳买卖股票时机系列题目的GO解法
This commit is contained in:
程序员Carl
2021-11-16 12:40:42 +08:00
committed by GitHub
5 changed files with 132 additions and 3 deletions

View File

@@ -272,6 +272,41 @@ class Solution:
return dp[2*k]
```
Go
版本一:
```go
// 买卖股票的最佳时机IV 动态规划
// 时间复杂度O(kn) 空间复杂度O(kn)
func maxProfit(k int, prices []int) int {
if k == 0 || len(prices) == 0 {
return 0
}
dp := make([][]int, len(prices))
status := make([]int, (2 * k + 1) * len(prices))
for i := range dp {
dp[i] = status[:2 * k + 1]
status = status[2 * k + 1:]
}
for j := 1; j < 2 * k; j += 2 {
dp[0][j] = -prices[0]
}
for i := 1; i < len(prices); i++ {
for j := 0; j < 2 * k; j += 2 {
dp[i][j + 1] = max(dp[i - 1][j + 1], dp[i - 1][j] - prices[i])
dp[i][j + 2] = max(dp[i - 1][j + 2], dp[i - 1][j + 1] + prices[i])
}
}
return dp[len(prices) - 1][2 * k]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```
```go
func maxProfit(k int, prices []int) int {