mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
新增 0123.买卖股票的最佳时机III.md Go解法
This commit is contained in:
@ -317,7 +317,38 @@ const maxProfit = prices => {
|
|||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Go:
|
||||||
|
|
||||||
|
> 版本一:
|
||||||
|
```go
|
||||||
|
// 买卖股票的最佳时机III 动态规划
|
||||||
|
// 时间复杂度O(n) 空间复杂度O(n)
|
||||||
|
func maxProfit(prices []int) int {
|
||||||
|
dp := make([][]int, len(prices))
|
||||||
|
status := make([]int, len(prices) * 4)
|
||||||
|
for i := range dp {
|
||||||
|
dp[i] = status[:4]
|
||||||
|
status = status[4:]
|
||||||
|
}
|
||||||
|
dp[0][0], dp[0][2] = -prices[0], -prices[0]
|
||||||
|
|
||||||
|
for i := 1; i < len(prices); i++ {
|
||||||
|
dp[i][0] = max(dp[i - 1][0], -prices[i])
|
||||||
|
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
|
||||||
|
dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] - prices[i])
|
||||||
|
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] + prices[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
return dp[len(prices) - 1][3]
|
||||||
|
}
|
||||||
|
|
||||||
|
func max(a, b int) int {
|
||||||
|
if a > b {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
Reference in New Issue
Block a user