@@ -297,8 +297,7 @@ class Solution {
297297
298298### Python:
299299
300- 版本一
301-
300+ > 版本一
302301``` python
303302class Solution :
304303 def maxProfit (self , k : int , prices : List[int ]) -> int :
@@ -313,7 +312,8 @@ class Solution:
313312 dp[i][j+ 2 ] = max (dp[i- 1 ][j+ 2 ], dp[i- 1 ][j+ 1 ] + prices[i])
314313 return dp[- 1 ][2 * k]
315314```
316- 版本二
315+
316+ > 版本二
317317``` python
318318class Solution :
319319 def maxProfit (self , k : int , prices : List[int ]) -> int :
@@ -329,9 +329,31 @@ class Solution:
329329 dp[j] = max (dp[j],dp[j- 1 ]+ prices[i])
330330 return dp[2 * k]
331331```
332+
333+ > 版本三: 一维 dp 数组(易理解版本)
334+ ``` python
335+ class Solution :
336+ def maxProfit (self , k : int , prices : List[int ]) -> int :
337+ dp = [0 ] * k * 2
338+ for i in range (k):
339+ dp[i * 2 ] = - prices[0 ]
340+
341+ for price in prices[1 :]:
342+ dc = dp.copy() # 这句话是关键,把前一天的 dp 状态保存下来,防止被覆盖掉,后面只用它,不用 dp,逻辑简单易懂
343+
344+ for i in range (2 * k):
345+ if i % 2 == 1 :
346+ dp[i] = max (dc[i], dc[i - 1 ] + price)
347+ else :
348+ pre = 0 if i == 0 else dc[i - 1 ]
349+ dp[i] = max (dc[i], pre - price)
350+
351+ return dp[- 1 ]
352+ ```
353+
332354### Go:
333355
334- 版本一:
356+ > 版本一:
335357
336358``` go
337359// 买卖股票的最佳时机IV 动态规划
@@ -368,7 +390,7 @@ func max(a, b int) int {
368390}
369391```
370392
371- 版本二: 三维 dp数组
393+ > 版本二: 三维 dp数组
372394``` go
373395func maxProfit (k int , prices []int ) int {
374396 length := len (prices)
@@ -443,7 +465,31 @@ func max(a, b int) int {
443465}
444466```
445467
468+ > 版本四:一维 dp 数组(易理解版本)
446469
470+ ``` go
471+ func maxProfit (k int , prices []int ) int {
472+ dp := make ([]int , 2 * k)
473+ for i := range k {
474+ dp[i * 2 ] = -prices[0 ]
475+ }
476+
477+ for j := 1 ; j < len (prices); j++ {
478+ dc := slices.Clone (dp) // 这句话是关键,把前一天的 dp 状态保存下来,防止被覆盖掉,后面只用它,不用 dp,逻辑简单易懂
479+
480+ for i := range k * 2 {
481+ if i % 2 == 1 {
482+ dp[i] = max (dc[i], dc[i - 1 ] + prices[j])
483+ } else {
484+ pre := 0 ; if i >= 1 { pre = dc[i - 1 ] }
485+ dp[i] = max (dc[i], pre - prices[j])
486+ }
487+ }
488+ }
489+
490+ return dp[2 * k - 1 ]
491+ }
492+ ```
447493
448494### JavaScript:
449495
0 commit comments