一、题目
二、代码
class Solution
{
public int maxProfit(int[] prices)
{
int i,j;
int length = prices.length;
int[][] dp = new int[length][4];
//持有
//卖出
//冷冻期
//保持卖出
dp[0][0] = -1 * prices[0];
for(i=1;i<length;i++)
{
dp[i][0] = Math.max(dp[i-1][0],Math.max(dp[i-1][2]-prices[i],dp[i-1][3]-prices[i]));
dp[i][1] = dp[i-1][0] +prices[i];
dp[i][2] = dp[i-1][1];
dp[i][3] = Math.max(dp[i-1][3],dp[i-1][2]);
}
return Math.max(dp[length-1][1],Math.max(dp[length-1][2],dp[length-1][3]));
}
}
三、运行结果
四 、附录
二刷
class Solution
{
public int maxProfit(int[] prices)
{
int i;
int length = prices.length;
int[][] res = new int[length][3];
//拥有 不拥有 不拥有且卖出
res[0][0] = -prices[0];
res[0][1] = 0;
res[0][2] = 0;
for(i=1;i<length;i++)
{
res[i][0] = Math.max(res[i-1][0] , res[i-1][1]-prices[i] );
res[i][1] = Math.max(res[i-1][1],res[i-1][2]);
res[i][2] = res[i-1][0]+prices[i];
}
return Math.max(res[length-1][1],res[length-1][2]);
}
}