Maximum sum two non-overlapping subarrays of given size in C++


In this problem, we are given an array of positive integers and a number k. Our task is to create a program that will find the maximum sum of two nonoverlapping subarrays of the given size(k).

So, basically we have two print two non-overlapping (distinct) subarrays that have the maximum sum and are of size k.

Let’s take an example to understand the problem,

Input

array = {7, 1, 6, 9, 2} , k = 2

Output

{7, 1} , {6, 9}

Explanation

all subarrays of size 2.
{7, 1} : sum = 7+1 = 8
{1, 6} : sum = 1+6 = 7
{6, 9} : sum = 6+9 = 15
{9, 2} : sum = 9+2 = 11
Two non-overlapping subarrays with max sums are {7,1} and {6,9}

To solve this problem, a simple solution will be to find all the subarrays and their sums and then check two maximum subarrays which do not overlap each other.

An effective approach to solving the problem will be using the prefix sum array which stores the sum of all elements until the element of the array. And the check for k elements the subarrays to find the subarray with the maximum sum.

Example

Program to show the implementation of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findSubArraySum(int sum[], int i, int j){
   if (i == 0)
      return sum[j];
   else
      return (sum[j] - sum[i - 1]);
}
void maxSubarray(int arr[],int N, int K){
   int prefixsum[N];
   prefixsum[0] = arr[0];
   for (int i = 1; i < N; i++)
   prefixsum[i] = prefixsum[i - 1] + arr[i];
   pair<int, int> resIndex = make_pair(N - 2 * K, N - K);
   int maxSubarraySum = findSubArraySum(prefixsum, N - 2 * K, N - K - 1) + findSubArraySum(prefixsum, N - K, N - 1);
   pair<int, int> secondSubarrayMax = make_pair(N - K, findSubArraySum(prefixsum, N - K, N - 1));
   for (int i = N - 2 * K - 1; i >= 0; i--){
      int cur = findSubArraySum(prefixsum, i + K, i + 2 * K - 1);
      if (cur >= secondSubarrayMax.second)
         secondSubarrayMax = make_pair(i + K, cur);
      cur = findSubArraySum(prefixsum, i, i + K - 1) + secondSubarrayMax.second;
      if (cur >= maxSubarraySum){
         maxSubarraySum = cur;
         resIndex = make_pair(i, secondSubarrayMax.first);
      }
   }
   cout<<"{ ";
   for (int i = resIndex.first; i <resIndex.first + K; i++)
      cout<<arr[i]<<" ";
   cout<<"}"<<endl<<"{ ";
   for (int i = resIndex.second; i < resIndex.second + K; i++)
      cout<<arr[i]<<" ";
   cout<<"}"<<endl;
}
int main(){
   int arr[] = {2, 5, 1, 2, 7, 3, 0};
   int N = sizeof(arr) / sizeof(int);
   int K = 2;
   cout<<"Two non-overlapping subarrays with maximum sum are \n";
   maxSubarray(arr, N, K);
   return 0;
}

Output

Two non-overlapping subarrays with maximum sum are
{ 2 5 }
{ 7 3 }

Updated on: 03-Jun-2020

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements