188. Best Time to Buy and Sell Stock IV 发表于 2022-02-17 123456789101112131415161718class Solution { public int maxProfit(int k, int[] prices) { int n = prices.length; int[][] dp = new int[n][2 * k + 1]; for (int i = 1; i <= k; i++) { dp[0][2 * i - 1] = -prices[0]; } for (int i = 1; i < n; i++) { for (int j = 1; j < 2 * k + 1; j++) { dp[i][j] = Math.max(dp[i - 1][j], dp[i - 1][j - 1] + (((j & 1) == 0 ? 1 : -1) * prices[i])); } } return dp[n - 1][2 * k]; // 因为同一天可以买卖多次,所以最大值一定能转移到该状态 }} Reference188. Best Time to Buy and Sell Stock IV