Check if the array has an element which is equal to sum of all the remaining elements | C ++ program to Check if the array has an element which is equal to sum of all the remaining elements ; Function to check if such element exists or not ; Storing frequency in map ; Stores the sum ; Traverse the array and count the array elements ; Only possible if sum is even ; If half sum is available ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isExists ( int a [ ] , int n ) { unordered_map < int , int > freq ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ a [ i ] ] ++ ; sum += a [ i ] ; } if ( sum % 2 == 0 ) { if ( freq [ sum / 2 ] ) return true ; } return false ; } int main ( ) { int a [ ] = { 5 , 1 , 2 , 2 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; if ( isExists ( a , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }