本文主要是介绍算法训练营day43(补),动态规划11,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
func max(a, b int) int {
if a > b {
return a
}
return b
}
//188. 买卖股票的最佳时机 IV
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]
}
//309. 买卖股票的最佳时机含冷冻期
//买卖股票的最佳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]))
}
//714. 买卖股票的最佳时机含手续费
//买卖股票的最佳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]
}
这篇关于算法训练营day43(补),动态规划11的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!