Check if the array has an element which is equal to sum of all the remaining elements | Java 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
import java . util . * ; class Solution { static boolean isExists ( int a [ ] , int n ) { Map < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq . put ( a [ i ] , freq . get ( a [ i ] ) == null ? 0 : freq . get ( a [ i ] ) + 1 ) ; sum += a [ i ] ; } if ( sum % 2 == 0 ) { if ( freq . get ( sum / 2 ) != null ) return true ; } return false ; } public static void main ( String args [ ] ) { int a [ ] = { 5 , 1 , 2 , 2 } ; int n = a . length ; if ( isExists ( a , n ) ) System . out . println ( " Yes " ) ; else System . out . println ( " No " ) ; } }