文章目录
力扣算法学习day35-1
188-买卖股票的最佳时机 IV
题目
代码实现
class Solution {
public int maxProfit(int k, int[] prices) {
if(k == 0 || prices.length == 0){
return 0;
}
// 原理和买卖股票的最佳时机 III 相同,从2笔交易拓展到k笔交易。
// dp[i][0] = Math.max(dp[i-1][0],-prices[i])
// dp[i][1] = Math.max(dp[i-1][1],prices[i] + dp[i-1][0])
// 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])
// dp[i][5] = Math.max(dp[i-1][5],dp[i-1][4] + prices[i])
// ......
int[][] dp = new int[prices.length][k * 2];
// 初始化
for(int i = 0;i < k * 2;i = i + 2){
dp[0][i] = -prices[0];
dp[0][i+1] = 0;
}
for(int i = 1;i < prices.length;i++){
dp[i][0] = Math.max(dp[i-1][0],-prices[i]);
// System.out.print(dp[i][0] + " ");
dp[i][1] = Math.max(dp[i-1][1],prices[i] + dp[i-1][0]);
// System.out.print(dp[i][1] + " ");
for(int j = 2;j < k * 2;j = j + 2){
dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-1] - prices[i]);
// System.out.print(dp[i][j] + " ");
dp[i][j+1] = Math.max(dp[i-1][j+1],dp[i-1][j] + prices[i]);
// System.out.print(dp[i][j+1] + " ");
}
// System.out.println();
}
// 求最大值
int max = dp[prices.length-1][1];
for(int i = 3;i < k * 2;i = i + 2){
if(dp[prices.length-1][i] > max){
max = dp[prices.length-1][i];
}
}
return max;
}
}