188.买卖股票的最佳时机4
虽然是困难,但是做了3之后也还好,不过是把状态替换成需要循环更新的状态而已。
class Solution {
public int maxProfit(int k, int[] prices) {
int[][] dp = new int[prices.length][2*k+1];
dp[0][0] = 0;
for(int i = 0;i < 2*k; i+=2){
dp[0][i+1] = -prices[0];
dp[0][i+2] = 0;
}
for(int i = 1; i <prices.length; i++){
for(int j = 0; j<2*k;j+=2){
dp[i][j+1] = Math.max(dp[i-1][j+1],dp[i-1][j]- prices[i]);
dp[i][j+2] = Math.max(dp[i-1][j+2],dp[i-1][j+1] + prices[i]);
}
}
return dp[prices.length - 1][2*k];
}
}
309.最佳买卖股票时机含冷冻期
越做到后面越觉得dp数组含义的重要,清楚了含义,递推公式起始就简单了。这题的关键在于冷冻期一定是当天卖出推出来的。
class Solution {
public int maxProfit(int[] prices) {
int[][] dp = new int[prices.length][4];
int min =Integer.MIN_VALUE;
//持有
dp[0][0] = -prices[0];
//保持不持有
dp[0][1] = 0;
//当天卖出
dp[0][2] = 0;
//冷冻期
dp[0][3] = 0;
for(int i = 1; i<prices.length; i++){
dp[i][0] = Math.max(dp[i-1][1] - prices[i],Math.max(dp[i-1][0],dp[i-1][3]-prices[i]));
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][3]);
dp[i][2] = dp[i-1][0] + prices[i];
dp[i][3] = dp[i-1][2];
}
return Math.max(dp[prices.length-1][1],Math.max(dp[prices.length-1][2],dp[prices.length-1][3]));
}
}
714.买卖股票的最佳时机含手续费
状态回到两个,持有和不持有,和第二题一样。唯一不一样的是卖出的时候扣除手续费
class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] dp = new int[prices.length ][2];
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i = 1 ; i< prices.length; i++){
//持有股票
dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] - prices[i]);
//不持有股票
dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i] - fee);
}
return dp[prices.length-1][1];
}
}