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

@@ -297,8 +297,7 @@ class Solution {
### Python:
版本一
> 版本一
```python
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
@@ -313,7 +312,8 @@ class Solution:
dp[i][j+2] = max(dp[i-1][j+2], dp[i-1][j+1] + prices[i])
return dp[-1][2*k]
```
版本二
> 版本二
```python
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
@@ -329,9 +329,31 @@ class Solution:
dp[j] = max(dp[j],dp[j-1]+prices[i])
return dp[2*k]
```
> 版本三: 一维 dp 数组(易理解版本)
```python
class Solution:
def maxProfit(self, k: int, prices: List[int]) -> int:
dp = [0] * k * 2
for i in range(k):
dp[i * 2] = -prices[0]
for price in prices[1:]:
dc = dp.copy() # 这句话是关键,把前一天的 dp 状态保存下来,防止被覆盖掉,后面只用它,不用 dp逻辑简单易懂
for i in range(2 * k):
if i % 2 == 1:
dp[i] = max(dc[i], dc[i - 1] + price)
else:
pre = 0 if i == 0 else dc[i - 1]
dp[i] = max(dc[i], pre - price)
return dp[-1]
```
### Go:
版本一:
> 版本一:
```go
// 买卖股票的最佳时机IV 动态规划
@@ -368,7 +390,7 @@ func max(a, b int) int {
}
```
版本二: 三维 dp数组
> 版本二: 三维 dp数组
```go
func maxProfit(k int, prices []int) int {
length := len(prices)
@@ -443,7 +465,31 @@ func max(a, b int) int {
}
```
> 版本四:一维 dp 数组(易理解版本)
```go
func maxProfit(k int, prices []int) int {
dp := make([]int, 2 * k)
for i := range k {
dp[i * 2] = -prices[0]
}
for j := 1; j < len(prices); j++ {
dc := slices.Clone(dp) // 这句话是关键,把前一天的 dp 状态保存下来,防止被覆盖掉,后面只用它,不用 dp逻辑简单易懂
for i := range k * 2 {
if i % 2 == 1 {
dp[i] = max(dc[i], dc[i - 1] + prices[j])
} else {
pre := 0; if i >= 1 { pre = dc[i - 1] }
dp[i] = max(dc[i], pre - prices[j])
}
}
}
return dp[2 * k - 1]
}
```
### JavaScript: