题目描述:
思路:一开始的思路是像以前做过的121. 买卖股票的最佳时机 122. 买卖股票的最佳时机 II 的想法来做,但是由于有冷却期的设置,因此想到了状态的转换,进而想到了动态规划。但是具体如何动态规划还是没有想法。于是–点开题解。。。题解将状态分为了三种,一种是持有当前股票的收益,一种是刚卖出有冷却期的收益,一种是卖出后无冷却期的收益。
对于持有当前股票的收益有两种情况:1.刚买入的 2.前一天已经持有的。
对于刚卖出有冷却期的收益只有可能是从前一天持有的状态刚刚卖出的。
对于没有冷却期的收益,要么是前一天就已经没有冷却期了,要么就是前一天有冷却期而现在没有了。
按照这个想法的代码:
class Solution {
public int maxProfit(int[] prices) {
if(prices.length==0)return 0;
int[][] result=new int[3][prices.length];
result[0][0]=-prices[0];
for(int i=1;i<prices.length;i++){
result[0][i]=Math.max(result[0][i-1],result[2][i-1]-prices[i]);
result[1][i]=result[0][i-1]+prices[i];
result[2][i]=Math.max(result[1][i-1],result[2][i-1]);
}
return Math.max(result[1][prices.length-1],result[2][prices.length-1]);
}
}
运行结果:
另外可以在空间复杂度上继续提高。使用6个变量或者2*3的数组来替代整个大的dp数组。