func max(a, b int) int {
if a > b {
return a
}
return b
}
func maxProfit4(k int, prices []int) int {
n := len(prices)
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]int, 2*k+1)
}
for i := 1; i < 2*k; {
dp[0][i] = -prices[0]
i = i + 2
}
for i := 1; i < n; i++ {
for j := 1; j < 2*k; {
//第K次买入后的利润
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1]-prices[i])
//第K次不持有的利润
dp[i][j+1] = max(dp[i-1][j+1], dp[i-1][j]+prices[i])
j = j + 2
}
}
return dp[n-1][2*k]
}
//买卖股票的最佳2的升级版
func maxProfit5(prices []int) int {
n := len(prices)
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]int, 4)
}
dp[0][0] = -prices[0]
for i := 1; i < n; i++ {
//买入后利润
dp[i][0] = max(dp[i-1][0], max(dp[i-1][1]-prices[i], dp[i-1][3]-prices[i]))
//保持卖出状态
dp[i][1] = max(dp[i-1][1], dp[i-1][3])
//卖出状态
dp[i][2] = dp[i-1][0] + prices[i]
//冷静期状态
dp[i][3] = dp[i-1][2]
}
return max(dp[n-1][1], max(dp[n-1][2], dp[n-1][3]))
}
//买卖股票的最佳2的升级版
func maxProfit6(prices []int, fee int) int {
n := len(prices)
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]int, 2)
}
dp[0][0] = -prices[0]
dp[0][1] = 0
for i := 1; i < n; i++ {
//买入后利润
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i])
//不持有的利润含有手续费
dp[i][1] = max(dp[i-1][1], dp[i-1][0]+prices[i]-fee)
}
return dp[n-1][1]
}