Maximize the subarray sum by choosing M subarrays of size K

Given an array arr containing N Positive integers, and two integers K and M, The task is to calculate the maximum amount of M Subsets of size K.


Pay attention reader! Do not stop learning now. Achieve all the important concepts of DSA with the Self-paced DSA course At a student-friendly price and be industry-ready. To complete your preparation from learning a language for DS Algo and many more, please see Full interview preparation course.

In case you want to participate Live lessons With experts, please refer DSA Live classes for working professionals and Competitive live programming for students.

input: arr[] = 1, 2, 1, 2, 6, 7, 5, 1, M = 3, K = 2
Productivity: 33
explanation: The three subsets selected are [2, 6], [6, 7] and [7, 5] Respectively. So, sum: 8 +12 +13 = 33

input: arr[] = 1, 4, 1, 0, 6, 7, 5, 9, M = 4 ,, K = 5
Productivity: seventy six

access: The problem can be solved by pre-calculating the prefix amount up to each index I am Who will tell us the sub-amount from 0 To I am. You can now use this prefix sum to find the sum of each K-size subset, using the formula:

Sub-array sum from i to j = prefix sum to j – sum prefix up to i

After finding the sum of all the subsets, select the maximum M Sub-amounts for calculating the answer.

To resolve this issue, follow these steps:

  1. Create a vector prefixSum Where each node represents the sum of the prefixes up to this index, plus another vector subarraySum, To store all subsets the sum of the size K.
  2. Now, run a loop from i = K To i = N And calculate the sum of each subset using the formula subarraySum[i-K, i]=prefixSum[i]-prefixSum[i-K] And push him Doctor subarraySum.
  3. Type subarraySum In descending order and add the top M Elements to get the answer.
  4. Print the answer according to the observation above.

The following is the application of the above approach:

C ++


#include <bits/stdc++.h>

using namespace std;


int maximumSum(vector<int>& arr, int M, int K)

    int N = arr.size();

    vector<int> prefixSum(N + 1, 0);



    for (int i = 1; i <= N; ++i)

        prefixSum[i] = prefixSum[i - 1]

                       + arr[i - 1];



    vector<int> subarraysSum;



    for (int i = K; i <= N; i++)



            - prefixSum[i - K]);







    int sum = 0;




    for (int i = 0; i < M; ++i)

        sum += subarraysSum[i];


    return sum;


int main()

    vector<int> arr = 1, 4, 1, 0, 6, 7, 5, 9 ;

    int M = 4, K = 5;

    cout << maximumSum(arr, M, K);

Time complexity: On)
Auxiliary space: On)




Please enter your comment!
Please enter your name here