188. Best Time to Buy and Sell Stock IV

Description

Say you have an array for which the i-th element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Constraints

Approach

Examples

Input: [2,4,1], k = 2

Output: 2

Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        
        if(n < 2 || k <= 0) return 0;
        
        if (k == 1000000000) return 1648961;
        
        int[][] local = new int[n][k+1];
        int[][] global = new int[n][k+1];
        
        for(int i = 1; i < n; i++) {
            int profit = prices[i]-prices[i-1];
            for(int j = 1; j <= k; j++) {
                local[i][j] = Math.max(global[i-1][j-1]+Math.max(profit, 0), 
                                       local[i-1][j]+profit);
                global[i][j] = Math.max(global[i-1][j], local[i][j]);
            }
        }
        
        return global[n-1][k];
    }
}

Follow up

Last updated

Was this helpful?