079_最佳买卖股票时机含冷冻期
知识点:动态规划
LeetCode第三百零九题:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
语言:GoLang
// dp,状态空间压缩
func maxProfit(prices []int) int {
length := len(prices)
if length == 0 {
return 0
}
dp_0, dp_1, dp_pre_2 := 0, -prices[0], 0
for i := 1; i < length; i++ {
// 今日的昨日,即明日的前日
tmp := dp_0
dp_0 = max(dp_0, dp_1 + prices[i])
dp_1 = max(dp_1, dp_pre_2 - prices[i])
dp_pre_2 = tmp
}
return dp_0
}
// dp
func maxProfit_(prices []int) int {
length := len(prices)
if length == 0 {
return 0
}
dp := make([][2]int, length)
for i := 0; i < length; i++ {
dp[i] = [2]int{}
}
dp[0][0], dp[0][1] = 0, -prices[0]
for i := 1; i < length; i++ {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i])
if i == 1 {
dp[i][1] = max(dp[i - 1][1], -prices[i])
} else {
dp[i][1] = max(dp[i - 1][1], dp[i - 2][0] - prices[i])
}
}
return dp[length - 1][0]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}