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

@@ -204,6 +204,40 @@ class Solution:
```
Go
```go
// 最佳买卖股票时机含冷冻期 动态规划
// 时间复杂度O(n) 空间复杂度O(n)
func maxProfit(prices []int) int {
n := len(prices)
if n < 2 {
return 0
}
dp := make([][]int, n)
status := make([]int, n * 4)
for i := range dp {
dp[i] = status[:4]
status = status[4:]
}
dp[0][0] = -prices[0]
for i := 1; i < n; i++ {
dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][1] - prices[i], dp[i - 1][3] - prices[i]))
dp[i][1] = max(dp[i - 1][1], dp[i - 1][3])
dp[i][2] = dp[i - 1][0] + prices[i]
dp[i][3] = dp[i - 1][2]
}
return max(dp[n - 1][1], max(dp[n - 1][2], dp[n - 1][3]))
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```
Javascript: