Monday, November 18, 2024
Google search engine
HomeData Modelling & AIMaximize the subarray sum by choosing M subarrays of size K

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 sum of M subarrays of size K.

Example:

Input: arr[] = {1, 2, 1, 2, 6, 7, 5, 1}, M = 3, K = 2
Output: 33
Explanation: The three chosen subarrays 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
Output: 76

 

Approach: The problem can be solved by precomputing the prefix sum till each index i which will tell us the sum of the subarray from 0 to i. Now this prefix sum can be used to find the sum of each subarray of size K, using the formula:

Subarray sum from i to j = Prefix sum till j – prefix Sum till i

After finding all subarrays sum, choose the maximum M subarray sums to calculate the answer. 
To solve this problem follow the below steps:

  1. Create a vector prefixSum in which each node represents the prefix sum till that index, and another vector subarraySum, to store all subarrays sum of size K.
  2. Now, run a loop from i=K to i=N and calculate the sum of each subarray using the formula subarraySum[i-K, i]=prefixSum[i]-prefixSum[i-K] and push it in vector subarraySum.
  3. Sort subarraySum in decreasing order and add the top M elements to get the answer.
  4. Print the answer according to the above observation.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the maximum
// sum of M subarrays of size K
int maximumSum(vector<int>& arr, int M, int K)
{
    int N = arr.size();
    vector<int> prefixSum(N + 1, 0);
 
    // Calculating prefix sum
    for (int i = 1; i <= N; ++i) {
        prefixSum[i] = prefixSum[i - 1]
                       + arr[i - 1];
    }
 
    vector<int> subarraysSum;
 
    // Finding sum of each subarray of size K
    for (int i = K; i <= N; i++) {
        subarraysSum.push_back(
            prefixSum[i]
            - prefixSum[i - K]);
    }
 
    sort(subarraysSum.begin(),
         subarraysSum.end(),
         greater<int>());
 
    int sum = 0;
 
    // Selecting the M maximum sums
    // to calculate the answer
    for (int i = 0; i < M; ++i) {
        sum += subarraysSum[i];
    }
    return sum;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 1, 4, 1, 0, 6, 7, 5, 9 };
    int M = 4, K = 5;
    cout << maximumSum(arr, M, K);
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate the maximum
// sum of M subarrays of size K
static  int maximumSum(int []arr, int M, int K)
{
    int N = arr.length;
    int []prefixSum = new int[N + 1];
 
    // Calculating prefix sum
    for (int i = 1; i <= N; ++i) {
        prefixSum[i] = prefixSum[i - 1]
                       + arr[i - 1];
    }
 
    Vector<Integer> subarraysSum = new Vector<Integer>();
 
    // Finding sum of each subarray of size K
    for (int i = K; i <= N; i++) {
        subarraysSum.add(
            prefixSum[i]
            - prefixSum[i - K]);
    }
 
    Collections.sort(subarraysSum,Collections.reverseOrder());
 
    int sum = 0;
 
    // Selecting the M maximum sums
    // to calculate the answer
    for (int i = 0; i < M; ++i) {
        sum += subarraysSum.get(i);
    }
    return sum;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 1, 4, 1, 0, 6, 7, 5, 9 };
    int M = 4, K = 5;
    System.out.print(maximumSum(arr, M, K));
}
}
 
// This code is contributed by 29AjayKumar


Python3




# python program for the above approach
 
# Function to calculate the maximum
# sum of M subarrays of size K
def maximumSum(arr, M, K):
 
    N = len(arr)
    prefixSum = [0 for _ in range(N + 1)]
 
    # Calculating prefix sum
    for i in range(1, N+1):
        prefixSum[i] = prefixSum[i - 1] + arr[i - 1]
 
    subarraysSum = []
 
    # Finding sum of each subarray of size K
    for i in range(K, N+1):
        subarraysSum.append(prefixSum[i] - prefixSum[i - K])
 
    subarraysSum.sort()
    sum = 0
 
    # Selecting the M maximum sums
    # to calculate the answer
    for i in range(0, M):
        sum += subarraysSum[i]
 
    return sum
 
# Driver Code
if __name__ == "__main__":
 
    arr = [1, 4, 1, 0, 6, 7, 5, 9]
    M = 4
    K = 5
    print(maximumSum(arr, M, K))
 
    # This code is contributed by rakeshsahni


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG
{
// Function to calculate the maximum
// sum of M subarrays of size K
static  int maximumSum(int []arr, int M, int K)
{
    int N = arr.Length;
    int []prefixSum = new int[N + 1];
 
    // Calculating prefix sum
    for (int i = 1; i <= N; ++i) {
        prefixSum[i] = prefixSum[i - 1]
                       + arr[i - 1];
    }
     
    List<int> subarraysSum = new List<int>();
 
    // Finding sum of each subarray of size K
    for (int i = K; i <= N; i++) {
        subarraysSum.Add(
            prefixSum[i]
            - prefixSum[i - K]);
    }
     
    subarraysSum.Sort();
    subarraysSum.Reverse();
     
    int sum = 0;
 
    // Selecting the M maximum sums
    // to calculate the answer
    for (int i = 0; i < M; ++i) {
        sum += subarraysSum[i];
    }
    return sum;
}
 
// Driver Code
public static void Main()
{
    int[] arr = { 1, 4, 1, 0, 6, 7, 5, 9 };
    int M = 4, K = 5;
    Console.Write(maximumSum(arr, M, K));
}
}
 
// This code is contributed by Samim Hossain Mondal


Javascript




<script>
// Javascript code for the above approach
  
// Function to calculate the maximum
// sum of M subarrays of size K
function maximumSum(arr, M, K)
{
    var N = arr.length;
    var prefixSum = Array(N + 1).fill(0);
 
    // Calculating prefix sum
    for (var i = 1; i <= N; ++i) {
        prefixSum[i] = prefixSum[i - 1]
                       + arr[i - 1];
    }
    var subarraysSum = [];
    var t = 0;
 
    // Finding sum of each subarray of size K
    for (var i = K; i <= N; i++) {
        subarraysSum[t++] =
            (prefixSum[i] - prefixSum[i - K]);
    }
     
    subarraysSum.sort();
    subarraysSum.reverse();
    var sum = 0;
 
    // Selecting the M maximum sums
    // to calculate the answer
    for (var i = 0; i < M; ++i) {
        sum += subarraysSum[i];
    }
    return sum;
}
 
// Driver Code
var arr = [ 1, 4, 1, 0, 6, 7, 5, 9 ];
var M = 4, K = 5;
document.write(maximumSum(arr, M, K));
 
// This code is contributed by Samim Hossain Mondal
</script>


 
 

Output

76

 

Time Complexity: O(N)
Auxiliary Space: O(N)

 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments