文章目录
买卖股票的最佳时机 IV
class Solution {
public int maxProfit(int k, int[] prices) {
int len = prices.length;
int [][][] dp = new int [len][k+1][2];
for(int j=0;j<=k;j++){
dp[0][j][0]=0;
dp[0][j][1]=-prices[0];
}
for(int i =1;i<len;i++){
dp[i][0][0]=0;
dp[i][0][1]=Math.max(dp[i-1][0][1],dp[i-1][0][0]-prices[i]);
}
for(int i=1;i<len;i++){
for(int j=1;j<=k;j++){
dp[i][j][0]=Math.max(dp[i-1][j][0],dp[i-1][j-1][1]+prices[i]);
dp[i][j][1]=Math.max(dp[i-1][j][1],dp[i-1][j][0]-prices[i]);
}
}
return dp[len-1][k][0];
}
}
买卖股票的最佳时机含手续费
就比一般类型的买卖股票多了个手续费,卖出股票时需要减去手续费即可
class Solution {
public int maxProfit(int[] prices, int fee) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}
}
最佳买卖股票时机含冷冻期
public class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
if (len < 2) {
return 0;
}
int[][] dp = new int[len][3];
dp[0][0] = 0;
dp[0][1] = -prices[0];
dp[0][2] = 0;
// dp[i][0]: 手上不持有股票,并且今天不是由于卖出股票而不持股,我们拥有的现金数
// dp[i][1]: 手上持有股票时,我们拥有的现金数
// dp[i][2]: 手上不持有股票,并且今天是由于卖出股票而不持股,我们拥有的现金数
for (int i = 1; i < len; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2]);
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
dp[i][2] = dp[i - 1][1] + prices[i];
}
return Math.max(dp[len - 1][0], dp[len - 1][2]);
}
}