Minimum positive integer required to split the array equally in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of N positive integers, the task is to find the smallest positive integer that can be placed between any two elements of the array such that, the sum of elements in the subarray occurring before it, is equal to the sum of elements occurring in the subarray after it, with the newly placed integer included in either of the two subarrays

Example

If arr = {3, 2, 1, 5, 7, 10} then output is 6. If we place value 6 in between 5 and 7 then sum of left and right subarray becomes equal as follows −

+ 2 + 1 + 5 + 6 = 17

7 + 10              = 17

Algorithm

  • Let the sum of the whole array by S
  • The idea is to find the left sum till index i(including it). Let this sum be L
  • Now the sum of the subarray arri+1 .. N is S – L. Let this sum be R
  • Since the sum of the two subarrays is supposed to be equal, the larger of the two above obtained sums L and R, should be reduced to the value of the smaller sum among these two and the difference between the larger sum and the smaller sum, will be the value of the positive integer required.

Example

#include <iostream>
#include <numeric>
#include <climits>
using namespace std;
int getMinimumSplitPoint(int *arr, int n) {
   int sum = 0;
   sum = accumulate(arr, arr + n, sum);
   int leftSum = 0;
   int rightSum = 0;
   int minValue = INT_MAX;
   for (int i = 0; i < n - 1; ++i) {
      leftSum += arr[i]; rightSum = sum - leftSum;
      if (leftSum > rightSum) {
         int e = leftSum - rightSum;
         if (e < minValue) {
            minValue = e;
         }
      } else {
         int e = rightSum - leftSum;
         if (e < minValue) {
            minValue = e;
         }
      }
   }
   return minValue;
}
int main() {
   int arr[] = {3, 2, 1, 5, 7, 10};
   int n = sizeof(arr) / sizeof(arr[0]);
   int minValue = getMinimumSplitPoint(arr, n);
   cout << "Element " << minValue << " needs to be inserted\n";
   return 0;
}

Output

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

Element 6 needs to be inserted
raja
Published on 22-Nov-2019 15:33:27
Advertisements