Difference between sum of odd and even frequent elements in an Array | Java program to find absolute difference between the sum of all odd frequenct and even frequent elements in an array ; Function to find the sum of all even and odd frequent elements in an array ; Stores the frequency of array elements ; Traverse the array ; Update frequency of current element ; Stores sum of odd and even frequent elements ; Traverse the map ; If frequency is odd ; Add sum of all occurrences of current element to sum_odd ; If frequency is even ; Add sum of all occurrences of current element to sum_even ; Calculate difference between their sum ; Return diff ; Driver Code
import java . util . * ; import java . io . * ; import java . math . * ; class GFG { static int findSum ( int arr [ ] , int N ) { Map < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! map . containsKey ( arr [ i ] ) ) map . put ( arr [ i ] , 1 ) ; else map . replace ( arr [ i ] , map . get ( arr [ i ] ) + 1 ) ; } int sum_odd = 0 , sum_even = 0 ; Set < Map . Entry < Integer , Integer > > hmap = map . entrySet ( ) ; for ( Map . Entry < Integer , Integer > data : hmap ) { int key = data . getKey ( ) ; int val = data . getValue ( ) ; if ( val % 2 != 0 ) sum_odd += ( key ) * ( val ) ; if ( val % 2 == 0 ) sum_even += ( key ) * ( val ) ; } int diff = sum_even - sum_odd ; return diff ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 5 , 5 , 2 , 4 , 3 , 3 } ; int N = arr . length ; System . out . println ( findSum ( arr , N ) ) ; } }