188.best-time-to-buy-and-sell-stock-iv.java 991 B

123456789101112131415161718192021222324252627
  1. class Solution {
  2. public int maxProfit(int k, int[] prices) {
  3. int profit = 0;
  4. if (prices.length == 0) return profit;
  5. if (prices.length / 2 < k) {
  6. for (int i = 1; i < prices.length; i++) {
  7. profit += Math.max(0, prices[i] - prices[i - 1]);
  8. }
  9. return profit;
  10. }
  11. int[][] dp = new int[k + 1][prices.length + 1];
  12. // dp[i][j] = max(
  13. // dp[i][j - 1],
  14. // max(dp[i - 1][l] + prices[j] - prices[l])
  15. // => prices[j] + max(dp[i - 1][l] - prices[l])
  16. // ), 0 <= l < j
  17. for (int i = 1; i <= k; i++) {
  18. int max = dp[i - 1][0] - prices[0];
  19. for (int j = 1; j <= prices.length; j++) {
  20. dp[i][j] = Math.max(dp[i][j - 1], prices[j - 1] + max);
  21. max = Math.max(max, dp[i - 1][j] - prices[j - 1]);
  22. profit = Math.max(profit, dp[i][j]);
  23. }
  24. }
  25. return profit;
  26. }
  27. }