Share my video https://youtu.be/3ZDZ-N0EPV0


  • 0
    T

    My code is like lot of code explained here. In addition I have a video explaining the solution.
    https://youtu.be/3ZDZ-N0EPV0

    public int maxProfit(int K, int[] prices) {
    if ( K == 0 || prices.length == 0) {
    return 0;
    }
    if ( K >= prices.length) {
    return allTimeProfit(prices);
    }
    int T[][] = new int[K+1][prices.length];

        for (int i = 1; i < T.length; i++) {
            int maxDiff = -prices[0];
            for (int j = 1; j < T[0].length; j++) {
                T[i][j] = Math.max(T[i][j-1], prices[j] + maxDiff);
                maxDiff = Math.max(maxDiff, T[i-1][j] - prices[j]);
            }
        }
        return T[K][prices.length-1];
    }
    
     public int allTimeProfit(int arr[]){
        int profit = 0;
        int localMin = arr[0];
        for(int i=1; i < arr.length;i++){
            if(arr[i-1] >= arr[i]){
                localMin = arr[i];
            }else{
                profit += arr[i] - localMin;
                localMin = arr[i];
            }
            
        }
        return profit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.