Check if the sum of K least and most frequent array elements are equal or not | C ++ program for the above approach ; Function to compare the sum of K most and least occurrences ; Stores frequency of array element ; Stores the frequencies as indexes and putelements with the frequency in a vector ; Find the frequency ; Insert in the vector ; Stores the count of elements ; Traverse the frequency array ; Find the kleastfreqsum ; If the count is K , break ; Reinitialize the count to zero ; Traverse the frequency ; Find the kmostfreqsum ; If the count is K , break ; Comparing the sum ; Otherwise , return No ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string checkSum ( int arr [ ] , int n , int k ) { unordered_map < int , int > m ; for ( int i = 0 ; i < n ; i ++ ) m [ arr [ i ] ] ++ ; vector < int > freq [ n + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { int f = m [ arr [ i ] ] ; if ( f != -1 ) { freq [ f ] . push_back ( arr [ i ] ) ; m [ arr [ i ] ] = -1 ; } } int count = 0 ; int kleastfreqsum = 0 ; for ( int i = 0 ; i <= n ; i ++ ) { for ( int x : freq [ i ] ) { kleastfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } count = 0 ; int kmostfreqsum = 0 ; for ( int i = n ; i >= 0 ; i -- ) { for ( int x : freq [ i ] ) { kmostfreqsum += x ; count ++ ; if ( count == k ) break ; } if ( count == k ) break ; } if ( kleastfreqsum == kmostfreqsum ) return " Yes " ; return " No " ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 2 , 3 , 3 , 4 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << checkSum ( arr , N , K ) ; return 0 ; }