Check if there exist two elements in an array whose sum is equal to the sum of rest of the array | C ++ program to find whether two elements exist whose sum is equal to sum of rest of the elements . ; Function to check whether two elements exist whose sum is equal to sum of rest of the elements . ; Find sum of whole array ; If sum of array is not even than we can not divide it into two part ; For each element arr [ i ] , see if there is another element with vaalue sum - arr [ i ] ; If element exist than return the pair ; Driver program .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPair ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; if ( sum % 2 != 0 ) return false ; sum = sum / 2 ; unordered_set < int > s ; for ( int i = 0 ; i < n ; i ++ ) { int val = sum - arr [ i ] ; if ( s . find ( val ) != s . end ( ) ) { printf ( " Pair ▁ elements ▁ are ▁ % d ▁ and ▁ % d STRNEWLINE " , arr [ i ] , val ) ; return true ; } s . insert ( arr [ i ] ) ; } return false ; } int main ( ) { int arr [ ] = { 2 , 11 , 5 , 1 , 4 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( checkPair ( arr , n ) == false ) printf ( " No ▁ pair ▁ found " ) ; return 0 ; }