mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 15:09:40 +08:00
添加0309.最佳买卖股票时机含冷冻期Go版本一维优化
This commit is contained in:
@ -357,6 +357,42 @@ func max(a, b int) int {
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// 一维优化版本
|
||||
// 时间复杂度O(n), 空间复杂度O(1)
|
||||
func maxProfit(prices []int) int {
|
||||
|
||||
// 0: 持有,一直持有和买入
|
||||
// 1: 不持有,一直不持有(不包含前一天卖出,因为这样的一天是冷静期,状态有区别)
|
||||
// 2:不持有,今天卖出
|
||||
// 3:冷静期,前一天卖出(一直不持有)
|
||||
dp0, dp1, dp2, dp3 := -prices[0], 0, 0, 0
|
||||
|
||||
n := len(prices)
|
||||
|
||||
for i := 1; i < n; i++ {
|
||||
t0 := max(dp0, max(dp1, dp3)-prices[i])
|
||||
t1 := max(dp1, dp3)
|
||||
t2 := dp0 + prices[i]
|
||||
t3 := dp2
|
||||
|
||||
// 更新
|
||||
dp0, dp1, dp2, dp3 = t0, t1, t2, t3
|
||||
}
|
||||
|
||||
return max(dp1, max(dp2, dp3))
|
||||
}
|
||||
|
||||
func max(a, b int) int {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
### Javascript:
|
||||
|
||||
> 不同的状态定义 感觉更容易理解些
|
||||
@ -540,3 +576,4 @@ impl Solution {
|
||||
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
|
||||
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
|
||||
</a>
|
||||
|
||||
|
Reference in New Issue
Block a user