Maximize frequency sum of K chosen characters from given string | Function to find the maximum sum of frequencies of the exactly K chosen characters from the string S ; Stores the resultant maximum sum ; Stores the frequency of array elements ; Find the frequency of character ; Sort the frequency array in the descending order ; Iterate to choose K elements greedily ; If the freq [ i ] cards are chosen ; K cards have been picked ; Return the resultant sum ; Driver Code
def maximumSum ( S , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE freq = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) ] += 1 NEW_LINE DEDENT freq = sorted ( freq ) [ : : - 1 ] NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( K > freq [ i ] ) : NEW_LINE INDENT sum += freq [ i ] * freq [ i ] NEW_LINE K -= freq [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sum += freq [ i ] * K NEW_LINE break NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " GEEKSFORGEEKS " NEW_LINE K = 10 NEW_LINE N = len ( S ) NEW_LINE print ( maximumSum ( S , N , K ) ) NEW_LINE DEDENT