Max sum of M non-overlapping subarrays of size K

Given an array and two numbers M and K. We need to find sum of max M subarrays of size K (non-overlapping) in the array. (Order of array remains unchanged). K is the size of subarrays and M is the count of subarray. It may be assumed that size of array is more than m*k. If total array size is not multiple of k, then we can take partial last array.

Examples :

Input: N = 7, M = 3, K = 1 
       arr[] = {2, 10, 7, 18, 5, 33, 0}; 
Output: 61 
Explanation: subsets are: 33, 18, 10 (3 subsets of size 1) 

Input: N = 4, M = 2, K = 2 
       arr[] = {3, 2, 100, 1}; 
Output:  106 
Explanation: subsets are: (3, 2), (100, 1) 2 subsets of size 2

Here we can see that the the we need to find M subarrays each of size K so,
1. We create a presum array, which contains in each index sum of all elements from ‘index‘ to ‘index + K’ in the given array. And size of the sum array will be n+1-k.
2. Now if we include the subarray of size k, then we can not include any of the elements of that subarray again in any other subarray as it will create overlapping subarrays. So we make recursive call by excluding the k elements of included subarray.
3. if we exclude a subarray then we can use the next k-1 elements of that subarray in other subarrays so we will make recursive call by just excluding the first element of that subarray.
4. At last return the max(included sum, excluded sum).




Output :


My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :
    Practice Tags :

    Be the First to upvote.

    Please write to us at to report any issue with the above content.