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
function maximumSum ( S , N , K ) { let sum = 0 ; let freq = Array . from ( { length : 256 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { freq [ S [ i ] . charCodeAt ( ) ] ++ ; } freq . sort ( ( a , b ) => b - a ) ; for ( let i = 0 ; i < 256 ; i ++ ) { if ( K > freq [ i ] ) { sum += freq [ i ] * freq [ i ] ; K -= freq [ i ] ; } else { sum += freq [ i ] * K ; break ; } } return sum ; } let S = " " ; let K = 10 ; let N = S . length ; document . write ( maximumSum ( S . split ( ' ' ) , N , K ) )