LeetCode 188: Best Time to Buy and Sell Stock IV

Problem Description

Explanation

To solve this problem, we can use dynamic programming. We will create a 2D array dp where dp[i][j] represents the maximum profit we can make up to day i with at most j transactions.

  1. Initialize the dp array with dimensions prices.length x k+1.
  2. Perform dynamic programming to fill in the dp array.
  3. Iterate through each day and each possible number of transactions to update the dp array based on two cases: not making a transaction on that day, or making a transaction on that day.
  4. The final answer will be dp[prices.length - 1][k].

Time Complexity: O(nk) Space Complexity: O(nk)

Solutions

class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }

        int n = prices.length;
        if (k >= n / 2) {
            int maxProfit = 0;
            for (int i = 1; i < n; i++) {
                if (prices[i] > prices[i - 1]) {
                    maxProfit += prices[i] - prices[i - 1];
                }
            }
            return maxProfit;
        }

        int[][] dp = new int[n][k + 1];
        for (int j = 1; j <= k; j++) {
            int maxDiff = -prices[0];
            for (int i = 1; i < n; i++) {
                dp[i][j] = Math.max(dp[i - 1][j], prices[i] + maxDiff);
                maxDiff = Math.max(maxDiff, dp[i][j - 1] - prices[i]);
            }
        }

        return dp[n - 1][k];
    }
}

Loading editor...