Remove an occurrence of most frequent array element exactly K times | Java program to implement 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
import java . util . * ; class GFG { static void maxFreqElements ( int arr [ ] , int N , int K ) { HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } while ( K > 0 ) { int max = 0 ; int element = 0 ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) { if ( i . getValue ( ) > max ) { max = i . getValue ( ) ; element = i . getKey ( ) ; } } System . out . print ( element + " ▁ " ) ; if ( mp . containsKey ( element ) ) { mp . put ( element , mp . get ( element ) + 1 ) ; } else { mp . put ( element , 1 ) ; } K -- ; } } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 3 , 2 , 1 , 4 , 1 } ; int N = arr . length ; int K = 2 ; maxFreqElements ( arr , N , K ) ; } }