https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
题目
分析
这里的「处于冷冻期」指的是在第 i 天结束之后的状态。也就是说:如果第 i 天结束之后处于冷冻期,那么第 i+1 天无法买入股票。
代码
class Solution {
public int maxProfit(int[] prices) {
int n=prices.length;
int[][] f=new int[n][3];
f[0][0]=-prices[0];//第0天持有股票,说明是第0天买的
f[0][1]=0;//今天结束后处于冷冻
f[0][2]=0;//今天结束后处于不冷冻
for(int i=1;i<n;i++){
//昨天持有 或 今天刚买(昨天结束后不在冷冻期)
f[i][0]=Math.max(f[i-1][0],f[i-1][2]-prices[i]);
//今天卖出变冷冻(昨天持有)
f[i][1]=f[i-1][0]+prices[i];
//今天结束后不冷冻且不持有,说明昨天也不持有,今天保持昨天的状态
f[i][2]=Math.max(f[i-1][1],f[i-1][2]);
}
return Math.max(f[n-1][1],f[n-1][2]);
}
}
空间优化过的代码
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)
return 0;
int n=prices.length;
//int[][] f=new int[n][3];
int f0=-prices[0];
int f1=0;
int f2=0;
int nf0,nf1,nf2;
for(int i=1;i<n;i++){
nf0=Math.max(f0,f2-prices[i]);
nf1=f0+prices[i];
nf2=Math.max(f1,f2);
//赋值给下一轮要用的f0,f1,f2
f0=nf0;
f1=nf1;
f2=nf2;
}
return Math.max(f1,f2);
}
}
结果
复杂度
时间复杂度O(N)
空间复杂度O(1)
二、
class Solution {
public int maxProfit(int[] prices) {
int len=prices.length;
if(len==0||len==1)
return 0;
int[] hold=new int[len];
int[] unhold=new int[len];
hold[0]=-prices[0];
unhold[0]=0;
hold[1]=Math.max(-prices[0],-prices[1]);
unhold[1]=Math.max(unhold[0],hold[0]+prices[1]);
for(int i=2;i<len;i++){
hold[i]=Math.max(hold[i-1],unhold[i-2]-prices[i]);
unhold[i]=Math.max(unhold[i-1],hold[i-1]+prices[i]);
}
return unhold[len-1];
}
}
class Solution {
public int maxProfit(int[] prices) {
int rest=0;
int sold=0;
int hold=Integer.MIN_VALUE;
int preSold,preHold;
for(int price:prices){
preSold=sold;
preHold=hold;
hold=Math.max(preHold,rest-price);
sold=preHold+price;
rest=Math.max(rest,preSold);
}
return Math.max(rest,sold);
}
}