LeetCode刷题记163
188. 买卖股票的最佳时机 IV
class Solution {
public int maxProfit(int k, int[] prices) {
if (prices.length == 0) return 0;
k = Math.min(prices.length / 2, k);
// 买入加卖出算一次交易
int[][] have = new int[prices.length][k + 1]; // 第i+1天经过j次交易手上有股票时的最大金额
int[][] not_have = new int[prices.length][k + 1]; // 第i+1天经过j次交易手上没有股票时的最大金额
// for (int i = 0; i < prices.length; i ++) {
Arrays.fill(have[0], (int)-1e6);
Arrays.fill(not_have[0], (int)-1e6);
// }
have[0][0] = -prices[0]; // 第1天买了才能满足手上有股票
not_have[0][0] = 0;
for (int i = 1; i < prices.length; i ++) {
for (int j = 0; j <= k; j ++) {
have[i][j] = Math.max(have[i - 1][j], not_have[i - 1][j] - prices[i]); // 之前买的,今天买的
if (j > 0) not_have[i][j] = Math.max(not_have[i - 1][j], have[i - 1][j - 1] + prices[i]);
}
}
return Arrays.stream(not_have[prices.length - 1]).max().getAsInt();
}
}
我好菜,不会做,看答案的。。。