class Solution {
public int maxProfit(int[] prices) {
// 1 2 3 0 2
/*
have[i]表示第i天持有股票的最大值
no[i]表示第i天没有持有股票的最大值
// 如果是不包含冷冻期
have[i] = max(have[i-1],no[i-1]-price[i]) (*)
no[i] = max(no[i-1],have[i-1]+price[i]) (**)
// 如果包含冷冻期
(*)需要修改,no[i-1] = 第i-1天持有,但是i-1天卖出了,此时冷冻,第二天不能交易
no[i-1] = 第i-1天不持有,那么no[i-1] = no[i-2]
have[i] = max(have[i-1],no[i-2]-price[i]) (*)
*/
int len = prices.length;
int[] have = new int[len];
int[] no = new int[len];
have[0] = -prices[0];
for(int i=1;i<len;i++){
if(i>=2){
have[i] = Math.max(have[i-1],no[i-2]-prices[i]);
}else{
have[i] = Math.max(-prices[0],-prices[1]);
}
no[i] = Math.max(no[i-1],have[i-1]+prices[i]);
}
return Math.max(have[len-1],no[len-1]);
}
}
leetcode309. 最佳买卖股票时机含冷冻期(dp)
最新推荐文章于 2024-04-20 23:28:15 发布