Minimum number of distinct elements after removing M items | Set 2 | Java program to implement the above approach ; Function to return minimum distinct character after M removals ; Count the occurences of number and store in count ; Count the occurences of the frequencies ; Take answer as total unique numbers and remove the frequency and subtract the answer ; Remove the minimum number of times ; Return the answer ; Driver code ; Initialize array ; Size of array ; Function call
import java . util . * ; class GFG { static int distinctNumbers ( int arr [ ] , int m , int n ) { Map < Integer , Integer > count = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) count . put ( arr [ i ] , count . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; int [ ] fre_arr = new int [ n + 1 ] ; for ( Integer it : count . values ( ) ) { fre_arr [ it ] ++ ; } int ans = count . size ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { int temp = fre_arr [ i ] ; if ( temp == 0 ) continue ; int t = Math . min ( temp , m / i ) ; ans -= t ; m -= i * t ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 4 , 1 , 5 , 3 , 5 , 1 , 3 } ; int n = arr . length ; int m = 2 ; System . out . println ( distinctNumbers ( arr , m , n ) ) ; } }