Remove an occurrence of most frequent array element exactly K times | 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 ; Given array ; Size of the array ; Given K
function maxFreqElements ( arr , N , K ) { var mp = { } ; for ( var i = 0 ; i < N ; i ++ ) { if ( mp . hasOwnProperty ( arr [ i ] ) ) { mp [ arr [ i ] ] ++ ; } else { mp [ arr [ i ] ] = 1 ; } } while ( K > 0 ) { var max = 0 ; var element = 0 ; for ( const [ key , value ] of Object . entries ( mp ) ) { if ( value > max ) { max = value ; element = key ; } } document . write ( element + " " ) ; if ( mp . hasOwnProperty ( element ) ) { mp [ element ] -- ; } else { mp [ element ] = - 1 ; } K -- ; } } var arr = [ 1 , 3 , 2 , 1 , 4 , 1 ] ; var N = arr . length ; var K = 2 ; maxFreqElements ( arr , N , K ) ;