

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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
- Elements to be added so that all elements of a range are present in array in C++
- Maximum number of edges to be added to a tree so that it stays a Bipartite graph in C++
- Program to find minimum number of characters to be added to make it palindrome in Python
- How to rescale a continuous variable so that the range of the rescale becomes 0 to 1 in R?
- Convert the array such that the GCD of the array becomes 1 in C++
- Program to find minimum deletions to make string balanced in Python
- Ways to remove one element from a binary string so that XOR becomes zero in C++
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space using C++
- How to find the minimum value of an array in JavaScript?
- Minimum number of Parentheses to be added to make it valid in C++
- Print elements that can be added to form a given sum
- Minimum flips in two binary arrays so that their XOR is equal to another array in C++.
Advertisements