LeetCode: 309. Best Time to Buy and Sell Stock with Cooldown
题目描述
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
Input: [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]
解题思路 —— 动态规划
-
dp[i+1][BUY]
表示前 i
天进入 BUY
状态的最大收益 -
dp[i+1][SELL]
表示前 i
天进入 SELL
状态的最大收益 -
dp[i+1][COOLDOWN]
表示前 i
天进入 COOLDOWN
状态的最大收益
AC 代码
func max(lhv, rhv int32) int32 {
if lhv > rhv {
return lhv
} else {
return rhv
}
}
func maxProfit(prices []int) int {
const (
BUY = iota
SELL
COOLDOWN
)
dp := make([][3]int32, len(prices)+1)
dp[0][0], dp[0][1], dp[0][2] = math.MinInt32, math.MinInt32, 0
for i := 0; i < len(prices); i++ {
dp[i+1][BUY] = max(dp[i][COOLDOWN] - int32(prices[i]), dp[i][BUY])
if dp[i][BUY] == math.MinInt32 {
dp[i+1][SELL] = math.MinInt32
} else {
dp[i+1][SELL] = dp[i][BUY] + int32(prices[i])
}
dp[i+1][COOLDOWN] = max(dp[i][SELL], dp[i][COOLDOWN])
}
return int(max(dp[len(prices)][COOLDOWN], dp[len(prices)][SELL]))
}