123.买卖股票的最佳时机III
func maxProfit(prices []int) int {
dp := make([][]int , len(prices))
dp[0] = []int{0, -prices[0], 0, -prices[0], 0}
for i := 1; i < len(prices);i++{
val0 := dp[i - 1][0]
val1 := max(dp[i - 1][0] - prices[i], dp[i - 1][1])
val2 := max(dp[i - 1][1] + prices[i], dp[i - 1][2])
val3 := max(dp[i - 1][2] - prices[i], dp[i - 1][3])
val4 := max(dp[i - 1][3] + prices[i], dp[i - 1][4])
dp[i] = []int{val0, val1, val2, val3, val4}
}
return dp[len(prices)- 1][4]
}
func max(a, b int)int{
if a < b{
return b
}
return a
}
● 188.买卖股票的最佳时机IV
和买卖股票3中的思路一样,只不过从两次换成了k次
func maxProfit(k int, prices []int) int {
dp := make([][]int, len(prices))
for i := 0; i < len(dp); i++{
tmp := make([]int, 2 * k + 1)
dp[i] = tmp
if i == 0{
for j := 1; j < 2 * k + 1; j += 2{
dp[i][j] = -prices[0]
}
}
}
for i := 1; i < len(dp); i++{
dp[i][0] = dp[i - 1][0]
for j :=1; j < 2 * k + 1; j += 2{
dp[i][j] = max(dp[i - 1][j - 1] - prices[i], dp[i - 1][j])
dp[i][j + 1] = max(dp[i - 1][j] + prices[i], dp[i - 1][j + 1])
}
}
return dp[len(prices) - 1][2 * k]
}
func max(a , b int)int{
if a < b{
return b
}
return a
}