File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -404,6 +404,47 @@ func max188(a, b int) int {
404404}
405405```
406406
407+ 版本三:空间优化版本
408+
409+ ``` go
410+ func maxProfit (k int , prices []int ) int {
411+ n := len (prices)
412+ // k次交易,2 * k种状态
413+ // 状态从1开始计算,避免判断
414+ // 奇数时持有(保持或买入)
415+ // 偶数时不持有(保持或卖出)
416+ dp := make ([][]int , 2 )
417+ dp[0 ] = make ([]int , k * 2 + 1 )
418+ dp[1 ] = make ([]int , k * 2 + 1 )
419+
420+ // 奇数状态时持有,i += 2
421+ for i := 1 ; i <= k * 2 ; i += 2 {
422+ dp[0 ][i] = -prices[0 ]
423+ }
424+
425+ for i := 1 ; i < len (prices); i++ {
426+ for j := 1 ; j <= k * 2 ; j++ {
427+ if j % 2 == 1 {
428+ dp[i % 2 ][j] = max (dp[(i - 1 ) % 2 ][j], dp[(i - 1 ) % 2 ][j - 1 ] - prices[i])
429+ } else {
430+ dp[i % 2 ][j] = max (dp[(i - 1 ) % 2 ][j], dp[(i - 1 ) % 2 ][j - 1 ] + prices[i])
431+ }
432+ }
433+ }
434+
435+ return dp[(n - 1 ) % 2 ][k * 2 ]
436+ }
437+
438+ func max (a , b int ) int {
439+ if a > b {
440+ return a
441+ }
442+ return b
443+ }
444+ ```
445+
446+
447+
407448### JavaScript:
408449
409450``` javascript
@@ -558,3 +599,4 @@ impl Solution {
558599<a href =" https://programmercarl.com/other/kstar.html " target =" _blank " >
559600 <img src =" ../pics/网站星球宣传海报.jpg " width =" 1000 " />
560601</a >
602+
You can’t perform that action at this time.
0 commit comments