Check if there exist two elements in an array whose sum is equal to the sum of rest of the array | Java 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 .
import java . util . * ; class GFG { static boolean 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 ; HashSet < Integer > s = new HashSet < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int val = sum - arr [ i ] ; if ( s . contains ( val ) && val == ( int ) s . toArray ( ) [ s . size ( ) - 1 ] ) { System . out . printf ( "Pair elements are %d and %dNEW_LINE", arr[i], val); return true ; } s . add ( arr [ i ] ) ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 11 , 5 , 1 , 4 , 7 } ; int n = arr . length ; if ( checkPair ( arr , n ) == false ) { System . out . printf ( " No ▁ pair ▁ found " ) ; } } }