- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Advertisements
To Continue Learning Please Login
Login with Google