Difference between sum of odd and even frequent elements in an Array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSum ( int arr [ ] , int N ) { unordered_map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } int sum_odd = 0 , sum_even = 0 ; for ( auto itr = mp . begin ( ) ; itr != mp . end ( ) ; itr ++ ) { if ( itr -> second % 2 != 0 ) sum_odd += ( itr -> first ) * ( itr -> second ) ; if ( itr -> second % 2 == 0 ) sum_even += ( itr -> first ) * ( itr -> second ) ; } int diff = sum_even - sum_odd ; return diff ; } int main ( ) { int arr [ ] = { 1 , 5 , 5 , 2 , 4 , 3 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findSum ( arr , N ) ; return 0 ; }