Remove an occurrence of most frequent array element exactly K times | C ++ program for the above approach ; Function to print the most frequent array element exactly K times ; Stores frequency array element ; Count frequency of array element ; Maximum array element ; Traverse the Map ; Find the element with maximum frequency ; If the frequency is maximum , store that number in element ; Print element as it contains the element having highest frequency ; Decrease the frequency of the maximum array element ; Reduce the number of operations ; Driver Code ; Given array ; Size of the array ; Given K
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxFreqElements ( int arr [ ] , int N , int K ) { map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { mp [ arr [ i ] ] ++ ; } while ( K > 0 ) { int max = 0 ; int element ; for ( auto i : mp ) { if ( i . second > max ) { max = i . second ; element = i . first ; } } cout << element << " ▁ " ; mp [ element ] -- ; K -- ; } } int main ( ) { int arr [ ] = { 1 , 3 , 2 , 1 , 4 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; maxFreqElements ( arr , N , K ) ; return 0 ; }