Find if array can be divided into two subarrays of equal sum in C++

C++Server Side ProgrammingProgramming

Suppose we have an array A. We have to check whether we can split the array into two parts, whose sum are equal. Suppose the elements are [6, 1, 3, 2, 5], then [6, 1], and [2, 5] can be two subarrays.

This problem can be solved easily by following these rules. We have to find the sum of all elements of the array at first, then for each element of the array, we can calculate the right sum by using total_sum – sum of elements found so far.

Example

#include<iostream>
#include<numeric>
using namespace std;
void displaySubArray(int arr[], int left, int right) {
   cout << "[ ";
   for (int i = left; i <= right; i++)
      cout << arr[i] << " ";
      cout << "] ";
   }
   void subarrayOfSameSum(int arr[] , int n) {
      int total_sum = accumulate(arr, arr+n, 0);
      int so_far_sum = 0;
      for(int i = 0; i<n; i++){
         if(2*so_far_sum+arr[i] == total_sum){
            cout << "subarray 1: "; displaySubArray(arr, 0, i-1);
            cout << "\nsubarray 2: "; displaySubArray(arr, i+1, n-1);
               return;
         }
         so_far_sum += arr[i];
      }
   cout << "No subarray can be formed";
}
int main() {
   int arr[] = {6, 1, 3, 2, 5} ;
   int n = sizeof(arr)/sizeof(arr[0]);
   subarrayOfSameSum(arr, n);
}

Output

subarray 1: [ 6 1 ]
subarray 2: [ 2 5 ]
raja
Published on 01-Nov-2019 09:54:12
Advertisements