top of page

Partition Array for Maximum Sum


Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray.


Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer.


class Solution {
    public int maxSumAfterPartitioning(int[] arr, int k) {
        int [] dp = new int[arr.length];
        Arrays.fill(dp, -1);
        return solve(0,arr, dp,k);
    }
    
    public int solve(int index, int[] arr, int[] dp, int k){
        if(index>=arr.length)
            return 0;
        
        if(dp[index]!=-1)
            return dp[index];
        
        int len = 0;
        int maxElement = 0;
        int maxAns = 0;
        for(int i=index;i<k+index&&i<arr.length;i++){
            len++;
            maxElement = Math.max(maxElement, arr[i]);
            int ans = maxElement * len + solve(i+1, arr, dp, k);
            if(ans>maxAns){
                maxAns = ans;
            }
        }
        dp[index] = maxAns;
        return dp[index];
    }
}

Recent Posts

See All

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page