题目:
给定一个整数数组prices,其中第 **prices[i] 表示第 i 天的股票价格 。
设计一个算法计算出最大利润。在满足以下约束条件下,你可以尽可能地完成更多的交易(多次买卖一支股票):
- 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
算法:
方法一:动态规划
总的来说根据每天操作类型,冷却无法操作,买入,卖出四种选择。
而根据持有状态划分,则是:不持有已冷却,不持有未冷却,持有三种状态。
如何进行合理的状态化是关键,状态不能太多,有了状态就好写转移方程。
func maxProfit(prices []int) int {
n := len(prices)
preProfit := [3]int{-prices[0], 0, 0}
curProfit := [3]int{-prices[0], 0, 0}
// dp[i][0] 持有股票的累计最大收益
// dp[i][1] 不持有股票在冷却期的累计最大收益(冷却期指下一天不能买入)
// dp[i][2] 不持有股票不在冷却期的累计最大收益
for i := 1; i < n; i ++ {
// 前一天就已经持有,或者今天新持有的
curProfit[0] = max(preProfit[0], preProfit[2] - prices[i])
// 前一天卖的
curProfit[1] = preProfit[0] + prices[i]
// 前一天卖的,或者在前一天之前就已经卖了
curProfit[2] = max(preProfit[1], preProfit[2])
preProfit = curProfit
}
return max(curProfit[1],curProfit[2])
}
func max(a, b int) int {
if a > b {
return a
}
return b
}