Skip to content

Commit

Permalink
review300: best time to buy and sell stock4
Browse files Browse the repository at this point in the history
  • Loading branch information
meooxx committed Apr 24, 2024
1 parent 127ea40 commit 1224304
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions bestTimeToBuyAndSellStock4/review300.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package main

import "math"

func maxProfit(k int, prices []int) int {
dpHold := make([]int, len(prices)+1)
dpProfit := make([]int, len(prices)+1)
dpHold[0] = math.MinInt32
dpProfit[0] = 0
max := func(a, b int) int {
if a > b {
return a
}
return b
}
for k > 0 {
for i := range prices {
// dpProfit[i+1], 只能使用k-1轮的盈利
// 不能使用dpProfit[i], 前面交易盈利, 单次交易
dpHold[i+1] = max(dpHold[i], dpProfit[i+1]-prices[i])
dpProfit[i+1] = max(dpProfit[i], prices[i]+dpHold[i])
}

k--
}
return dpProfit[len(prices)]
}

0 comments on commit 1224304

Please sign in to comment.