Maximize frequency sum of K chosen characters from given string
Input: K – 3, S = ”GEEKSFORGEEKS”
Choose the character E from the given string S, the sum of frequency of 3 E’s is 3*4 = 12, which is the maximum.
Input: K = 10, S = ”GEEKSFORGEEKS”
Approach: The given problem can be solved by using the Greedy Approach by choosing those K characters having the higher frequencies. Follow the steps below to solve the problem:
- Initialize a variable, say sum to 0 that stores the resultant sum of frequencies of exactly K chosen characters from the string S.
- Find the frequencies of each character in the string S and store it in an auxiliary array, say freq.
- Sort the array freq in descending order.
- Traverse the array freq and perform the following:
- If the current frequency is less than K, then add freq[i]*freq[i] to the variable sum as it maximizes the resultant sum and decrements the value of freq[i] from K as freq[i] characters are chosen.
- Otherwise, add the value of K*freq[i] to the variable sum and break out of the loop as K characters have been chosen.
- After completing the above steps, print the value of the sum as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(26)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.