123.买卖股票的最佳时机III
文章来源:https://www.toymoban.com/news/detail-683767.html
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次文章来源地址https://www.toymoban.com/news/detail-683767.html
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
}
到了这里,关于day 43 | ● 123.买卖股票的最佳时机III ● 188.买卖股票的最佳时机IV的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!