123.买卖股票的最佳时机III
看完题后的思路
- dp[i][]
0:没有操作 (其实我们也可以不设置这个状态)
1:第一次持有股票
2:第一次不持有股票
3:第二次持有股票
4:第二次不持有股票 - 递推公式
dp[i][1] = max(- prices[i], dp[i - 1][1]);
dp[i][2] = max(dp[i - 1][1] + prices[i], dp[i - 1][2])
dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);
dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);
3. 初始化
dp[0][0]=0;
dp[0][1]=-price[0];
dp[0][2]=0; // 买了 又卖出
dp[0][3]=-price[0]; // 买 卖 买
dp[0][4]=0 // 买 卖 买 卖
代码
public int maxProfit(int[] prices) {
int[][] dp=new int[prices.length][5];
dp[0][0]=0;
dp[0][1]=-prices[0];
dp[0][2]=0;
dp[0][3]=-prices[0];
dp[0][4]=0;
for (int i = 1; i <prices.length ; i++) {
dp[i][1]=Math.max(dp[i-1][1],-prices[i]);
dp[i][2]=Math.max(dp[i-1][2],dp[i-1][1]+prices[i]);
dp[i][3]=Math.max(dp[i-1][3],dp[i-1][2]-prices[i]);
dp[i][4]=Math.max(dp[i-1][4],dp[i-1][3]+prices[i]);
}
return Math.max(Math.max(dp[prices.length-1][2],dp[prices.length-1][4]),0);
}
}
188.买卖股票的最佳时机IV 任意次买卖
代码
public int maxProfit(int k, int[] prices) {
int[][] dp=new int[prices.length][2*k+1];
// 初始化
dp[0][0]=0;
for (int i = 1; i <2*k+1; i++) {
if (i%2==0){
dp[0][i]=0;
}else{
dp[0][i]=-prices[0];
}
}
// 核心
for (int i = 1; i <prices.length ; i++) {
for (int j = 1; j <2*k+1 ; j++) {
if (j%2==0){
dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-1]+prices[i]);
}else {
dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-1]-prices[i]);
}
}
}
int maxProfit=0;
for (int i = 0; i <2*k+1 ; i++) {
maxProfit=Math.max(dp[prices.length-1][i],maxProfit);
}
return maxProfit;
}