Suppose we have an array A, it has n elements. Our task is to divide the array A into two subarrays, such that the sum of each subarray will be the same. Suppose the array A = [2, 3, 4, 1, 4, 5], The output is 1, so subarrays before 1 and after 1 are taken. [2, 3, 4], and [4, 5].
To solve this problem, we will calculate the whole array except for the first element in right_sum. Consider that is the partitioning element. We will traverse from left to right. Subtracting an element from right_sum and adding an element to left_sum, we take the point when right_sum = left_sum.
Example
#include<iostream>
using namespace std;
int getPartitionElement(int arr[], int size) {
int right = 0, left = 0;
for (int i = 1; i < size; i++)
right += arr[i];
for (int i = 0, j = 1; j < size; i++, j++) {
right -= arr[j];
left += arr[i];
if (left == right)
return arr[i + 1];
}
return -1;
}
int main() {
int arr[] = { 2, 3, 4, 1, 4, 5 };
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Partition element: " << getPartitionElement(arr, size);
}Output
Partition element: 1