Maximum non | Java program for the above approach ; Function to find maximum distinct character after removing K character ; Freq implemented as hash table to store frequency of each character ; Store frequency of each character ; Insert each frequency in v ; Sort the freq of character in non - decreasing order ; Traverse the vector ; Update v [ i ] and k ; If K is still not 0 ; Store the final answer ; Count this character if freq 1 ; Return count of distinct characters ; Driver Code ; Given String ; Given k ; Function Call
import java . util . * ; class GFG { static int maxDistinctChar ( char [ ] s , int n , int k ) { HashMap < Integer , Integer > freq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . containsKey ( ( int ) s [ i ] ) ) { freq . put ( ( int ) s [ i ] , freq . get ( ( int ) s [ i ] ) + 1 ) ; } else { freq . put ( ( int ) s [ i ] , 1 ) ; } } Vector < Integer > v = new Vector < Integer > ( ) ; for ( Map . Entry < Integer , Integer > it : freq . entrySet ( ) ) { v . add ( it . getValue ( ) ) ; } Collections . sort ( v ) ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = Math . min ( v . get ( i ) - 1 , k ) ; v . set ( i , v . get ( i ) - mn ) ; k -= mn ; } if ( k > 0 ) { for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mn = Math . min ( v . get ( i ) , k ) ; v . set ( i , v . get ( i ) - mn ) ; k -= mn ; } } int res = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) if ( v . get ( i ) == 1 ) res ++ ; return res ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . length ( ) ; int K = 1 ; System . out . print ( maxDistinctChar ( S . toCharArray ( ) , N , K ) ) ; } }