
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 Element in Array Where Left Sum Equals Right Sum Using C++
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
Advertisements