Maximum non | C # 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 readonly answer ; Count this character if freq 1 ; Return count of distinct characters ; Driver Code ; Given String ; Given k ; Function call
using System ; using System . Collections . Generic ; class GFG { static int maxDistinctChar ( char [ ] s , int n , int k ) { Dictionary < int , int > freq = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( freq . ContainsKey ( ( int ) s [ i ] ) ) { freq [ ( int ) s [ i ] ] = freq [ ( int ) s [ i ] ] + 1 ; } else { freq . Add ( ( int ) s [ i ] , 1 ) ; } } List < int > v = new List < int > ( ) ; foreach ( KeyValuePair < int , int > it in freq ) { v . Add ( it . Value ) ; } v . Sort ( ) ; for ( int i = 0 ; i < v . Count ; i ++ ) { int mn = Math . Min ( v [ i ] - 1 , k ) ; v [ i ] = v [ i ] - mn ; k -= mn ; } if ( k > 0 ) { for ( int i = 0 ; i < v . Count ; i ++ ) { int mn = Math . Min ( v [ i ] , k ) ; v [ i ] = v [ i ] - mn ; k -= mn ; } } int res = 0 ; for ( int i = 0 ; i < v . Count ; i ++ ) if ( v [ i ] == 1 ) res ++ ; return res ; } public static void Main ( String [ ] args ) { String S = " geeksforgeeks " ; int N = S . Length ; int K = 1 ; Console . Write ( maxDistinctChar ( S . ToCharArray ( ) , N , K ) ) ; } }