Maximize frequency sum of K chosen characters from given string
Given a positive integer K and a string S consisting of N characters, the task is to maximize the sum of the frequencies of exactly K chosen characters from the 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(256)
My Personal Notes arrow_drop_up
Please Login to comment...