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

C++Server Side ProgrammingProgramming

Description

Given an array, we need to find two subarrays with a specific length K such that the sum of these subarrays is maximum among all possible choices of subarrays.

If input array is {12, 15, 10, 12, 17, 30, 8} and k = 2 then we can get following two sub-arrays of size 2 −

1. Arr1 = {12, 15}
2. Arr2 = {17, 30}

Algorithm

1. First we store the prefix sum in a separate array so that any subarray sum can be 
   calculated in constant time
2. After that we will initialize our two subarray from (N – 2K) and (N – K) indices, 
   where N is the length of the array and K is required subarray length
3. Then we will move from (N – 2K) index towards 0 and each time we will check whether 
   subarray sum at current index and subarray sum at (current index + K) is greater 
   than previously chosen subarray or not if they are, then update the summation
4. We can see here that as we need to maximize our sum, we can treat both subarrays independently. 
   At each index we will check subarray sum at current index and subarray sum at K distance away 
   and we will choose maximum sum independently and update the final answer as summation of both these array

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getSubarraySum(int *sum, int start, int end){
   if (start == 0) {
      return sum[end];
   }
   return (sum[end] - sum[start - 1]);
}
void getMaxSum(int arr[], int n, int k){
   int sum[n];
   sum[0] = arr[0];
   for (int i = 1; i < n; ++i) {
      sum[i] = sum[i - 1] + arr[i];
   }
   pair<int, int> resIndex = make_pair(n - 2 * k, n - k);
   int maxSum2Subarray = getSubarraySum(sum, n - 2 * k, n - k - 1) +
getSubarraySum(sum, n - k, n - 1);
   pair<int, int> secondSubarrayMax = make_pair(n - k, getSubarraySum(sum, n - k, n - 1));
   for (int i = n - 2 * k - 1; i >= 0; --i) {
      int cur = getSubarraySum(sum, i + k, i + 2 * k - 1);
      if (cur >= secondSubarrayMax.second) {
         secondSubarrayMax = make_pair(i + k, cur);
      }
      cur = getSubarraySum(sum, i, i + k - 1) + secondSubarrayMax.second;
      if (cur >= maxSum2Subarray) {
         maxSum2Subarray = cur;
         resIndex = make_pair(i, secondSubarrayMax.first);
      }
   }
   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[] = {12, 15, 10, 12, 17, 30, 8};
   int n = sizeof(arr) / sizeof(int);
   int k = 2;
   cout << "Result:\n";
   getMaxSum(arr, n, k);
   return 0;
}

Output

When you compile and execute the above program. It generates the following output −

12 15
17 30
raja
Published on 10-Feb-2020 09:27:51
Advertisements