Maximum non | Python3 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
from collections import defaultdict NEW_LINE def maxDistinctChar ( s , n , k ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ s [ i ] ] += 1 NEW_LINE DEDENT v = [ ] NEW_LINE for it in freq . values ( ) : NEW_LINE INDENT v . append ( it ) NEW_LINE DEDENT v . sort ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT mn = min ( v [ i ] - 1 , k ) NEW_LINE v [ i ] -= mn NEW_LINE k -= mn NEW_LINE DEDENT if ( k > 0 ) : NEW_LINE INDENT for i in range ( len ( v ) ) : NEW_LINE INDENT mn = min ( v [ i ] , k ) ; NEW_LINE v [ i ] -= mn NEW_LINE k -= mn NEW_LINE DEDENT DEDENT res = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ i ] == 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE N = len ( S ) NEW_LINE K = 1 NEW_LINE print ( maxDistinctChar ( S , N , K ) ) NEW_LINE DEDENT