0123, 0188, 0309 股票类问题,增加易理解的一维 dp Python 和 Go 版本。

This commit is contained in:
Lane Zhang
2024-11-22 10:57:51 +08:00
parent 0504beeca6
commit 5e0ab49475
3 changed files with 110 additions and 10 deletions

View File

@@ -316,8 +316,9 @@ class Solution:
### Go:
> 版本一
```go
// 版本一
func maxProfit(prices []int) int {
dp := make([][]int, len(prices))
for i := 0; i < len(prices); i++ {
@@ -345,8 +346,9 @@ func max(a, b int) int {
}
```
> 版本二
```go
// 版本二
func maxProfit(prices []int) int {
if len(prices) == 0 {
return 0
@@ -371,8 +373,9 @@ func max(x, y int) int {
}
```
> 版本三
```go
// 版本三
func maxProfit(prices []int) int {
if len(prices) == 0 {
return 0
@@ -397,6 +400,26 @@ func max(x, y int) int {
}
```
> 版本四:一维 dp 易懂版本
```go
func maxProfit(prices []int) int {
dp := make([]int, 4)
dp[0] = -prices[0]
dp[2] = -prices[0]
for _, price := range prices[1:] {
dc := slices.Clone(dp) // 这句话是关键,把前一天的 dp 状态保存下来,防止被覆盖掉,后面只用它,不用 dp逻辑简单易懂
dp[0] = max(dc[0], -price)
dp[1] = max(dc[1], dc[0] + price)
dp[2] = max(dc[2], dc[1] - price)
dp[3] = max(dc[3], dc[2] + price)
}
return dp[3]
}
```
### JavaScript:
> 版本一: