Skip to content

Commit 0846cd1

Browse files
committed
添加0309.最佳买卖股票时机含冷冻期Go版本一维优化
1 parent 5de44c3 commit 0846cd1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

problems/0309.最佳买卖股票时机含冷冻期.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,42 @@ func max(a, b int) int {
357357
}
358358
```
359359

360+
```go
361+
// 一维优化版本
362+
// 时间复杂度O(n), 空间复杂度O(1)
363+
func maxProfit(prices []int) int {
364+
365+
// 0: 持有,一直持有和买入
366+
// 1: 不持有,一直不持有(不包含前一天卖出,因为这样的一天是冷静期,状态有区别)
367+
// 2:不持有,今天卖出
368+
// 3:冷静期,前一天卖出(一直不持有)
369+
dp0, dp1, dp2, dp3 := -prices[0], 0, 0, 0
370+
371+
n := len(prices)
372+
373+
for i := 1; i < n; i++ {
374+
t0 := max(dp0, max(dp1, dp3)-prices[i])
375+
t1 := max(dp1, dp3)
376+
t2 := dp0 + prices[i]
377+
t3 := dp2
378+
379+
// 更新
380+
dp0, dp1, dp2, dp3 = t0, t1, t2, t3
381+
}
382+
383+
return max(dp1, max(dp2, dp3))
384+
}
385+
386+
func max(a, b int) int {
387+
if a > b {
388+
return a
389+
}
390+
return b
391+
}
392+
```
393+
394+
395+
360396
### Javascript:
361397

362398
> 不同的状态定义 感觉更容易理解些
@@ -540,3 +576,4 @@ impl Solution {
540576
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
541577
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
542578
</a>
579+

0 commit comments

Comments
 (0)