
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find an element in array such that sum of left array is equal to sum of right array 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
- Related Articles
- Find if array has an element whose value is half of array sum in C++
- Find sum of factorials in an array in C++
- Reduce an array to the sum of every nth element - JavaScript
- Maximum possible sum of a window in an array such that elements of same window in other array are unique in c++
- Sorting and find sum of differences for an array using JavaScript
- How to find the sum of elements of an Array using STL in C++?
- Check if the array has an element which is equal to sum of all the remaining elements in Python
- Find an array element such that all elements are divisible by it using c++
- Split Array with Equal Sum in C++
- Java program to find the sum of elements of an array
- Array element with minimum sum of absolute differences?
- C Program to find sum of perfect square elements in an array using pointers.
- Find number of pairs in an array such that their XOR is 0 using C++.
- Finding sum of every nth element of array in JavaScript
- Program to print Sum Triangle of an array.

Advertisements