Find the minimum value to be added so that array becomes balanced in C++

Suppose we have an array A with n elements. And the n is even. We have to find the value that needs to balance the array. As the size of the array is even, then we can make two halves. Sum of the left half and sum of the right half needs to be balanced. So if the array is like A = [1, 2, 3, 2, 5, 3] The sum of left half is 6, and sum of right half is 10. so we need 4 to balance the array.

The task is simple, we will find the sum of first and second halves, then find the absolute difference and return.


 Live Demo

using namespace std;
int getValueToBalance(int a[], int n) {
   int left_sum = 0;
   for (int i = 0; i < n/2; i++)
   left_sum += a[i];
   int right_sum = 0;
   for (int i = n/2; i < n; i++)
   right_sum += a[i];
   return abs(left_sum - right_sum);
int main() {
   int arr[] = {1, 2, 3, 2, 5, 3};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "The number for balancing: " << getValueToBalance(arr, n);


The number for balancing: 4