188. 买卖股票的最佳时机 IV - 力扣(LeetCode)
class Solution {
public int maxProfit(int k, int[] prices) {
int[][] dp = new int[prices.length][2*k];
for(int i=0;i<2*k;i++){
if(i%2 == 0){
dp[0][i] = -prices[0];
}else{
dp[0][i] = 0;
}
}
for(int i=1;i<prices.length;i++){
for(int j=0;j<2*k;j++){
if(j%2==0){ //持有
if(j==0){
dp[i][j] = Math.max(dp[i-1][j],-prices[i]);
}else{
dp[i][j] = Math.max(dp[i-1][j],-prices[i] + dp[i-1][j-1]);
}
}else{ //不持有
dp[i][j] = Math.max(dp[i-1][j],prices[i] + dp[i-1][j-1]);
}
}
}
int result = 0;
for(int i=0;i<2*k;i++){
if(i%2 != 0){
result = Math.max(result,dp[prices.length-1][i]);
}
}
return result;
}
}
309. 买卖股票的最佳时机含冷冻期 - 力扣(LeetCode)
class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1){
return 0;
}
int[][] dp = new int[prices.length][4];
dp[0][0] = -prices[0]; //第i天持有状态的最大收益
dp[0][1] = 0; //第i天保持卖出状态的收益
dp[0][2] = 0; //第i天卖出
dp[0][3] = 0; //第i天为冻结器的收益
for(int i=1;i<prices.length;i++){
dp[i][0] = Math.max(Math.max(dp[i-1][0],-prices[i]+dp[i-1][1]),-prices[i]+dp[i-1][3]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][3]);
dp[i][2] = prices[i] + dp[i-1][0];
dp[i][3] = dp[i-1][2];
}
return Math.max(Math.max(dp[prices.length-1][1],dp[prices.length-1][2]),dp[prices.length-1][3]);
}
}
714. 买卖股票的最佳时机含手续费 - 力扣(LeetCode)
class Solution {
public int maxProfit(int[] prices, int fee) {
int[][] dp = new int[prices.length][2];
dp[0][0] = -prices[0]; //第i天持有
dp[0][1] = 0; //第i天不持有
for(int i=1;i<prices.length;i++){
dp[i][0] = Math.max(dp[i-1][0],-prices[i]+dp[i-1][1]);
dp[i][1] = Math.max(dp[i-1][1],prices[i]+dp[i-1][0]-fee);
}
return dp[prices.length-1][1];
}
}