- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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.

## Example

#include<iostream> #include<cmath> 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); }

## Output

The number for balancing: 4

- Related Articles
- Find minimum value to assign all array elements so that array product becomes greater in C++
- Add minimum number to an array so that the sum becomes even in C++?
- Add minimum number to an array so that the sum becomes even in C programming
- Find the smallest number which must be added to 2300 so that it becomes a perfect square.
- Elements to be added so that all elements of a range are present in array in C++
- What should be added to each term of the ratio 7:13 so that their ratio becomes 2:3?
- What number must be added to each term of the ratio 7 : 12, so that the ratio becomes 4 : 5?
- Find the smallest number by which 85176 must be divided so that it becomes a perfect square
- Find the smallest number by which 4851 must be multiplied so that the product becomes a perfect square.
- Find the smallest number by which 28812 must be divided so that the quotient becomes a perfect square.
- What must be added to the numbers 6,10,14 and 22 so that they are in proportion?
- Find the value of m so that:
- Find the maximum possible value of the minimum value of modified array in C++
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph in C++
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.

Advertisements