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
using System ; using System . Collections . Generic ; class GFG { static void maxFreqElements ( int [ ] arr , int N , int K ) { Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . ContainsKey ( arr [ i ] ) ) { mp [ arr [ i ] ] ++ ; } else { mp [ arr [ i ] ] = 1 ; } } while ( K > 0 ) { int max = 0 ; int element = 0 ; foreach ( KeyValuePair < int , int > i in mp ) { if ( i . Value > max ) { max = i . Value ; element = i . Key ; } } Console . Write ( element + " ▁ " ) ; if ( mp . ContainsKey ( element ) ) { mp [ element ] -- ; } else { mp [ element ] = - 1 ; } K -- ; } } static void Main ( ) { int [ ] arr = { 1 , 3 , 2 , 1 , 4 , 1 } ; int N = arr . Length ; int K = 2 ; maxFreqElements ( arr , N , K ) ; } }