Minimum removals required to make frequency of each array element equal to its value | Java program to implement the above approach ; Function to find the minimum count of elements required to be removed such that frequency of arr [ i ] equal to arr [ i ] ; Stores frequency of each element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores minimum count of removals ; Traverse the map ; Stores key value of the map ; If frequency of i is less than i ; Update cntMinRem ; If frequency of i is greater than i ; Update cntMinRem ; Driver Code
import java . util . * ; class GFG { public static int min_elements ( int arr [ ] , int N ) { Map < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { mp . put ( arr [ i ] , mp . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; } int cntMinRem = 0 ; for ( int key : mp . keySet ( ) ) { int i = key ; int val = mp . get ( i ) ; if ( val < i ) { cntMinRem += val ; } else if ( val > i ) { cntMinRem += ( val - i ) ; } } return cntMinRem ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 4 , 2 } ; System . out . println ( min_elements ( arr , arr . length ) ) ; } }