Maximize the String value by assigning values in range [1, 26] to each character
Given a string S of size N, the task is to find the maximum sum of values assigned to all the alphabets of the string S. The value assigned to all the characters are over the range [1, 26], and the values assigned to the same lowercase and uppercase character is the same.
Input: S = “pQrqQPR”
The value of the letter ‘P’ is taken as 25, ‘Q’ is taken as 26, ‘R’ is taken as 24. Now, the sum of values assigned to the characters of the string is 25 + 26 + 24 + 26 + 26 + 25 + 24 = 176, which is maximum among all possible combinations of assigning values.
Input: S = “#aAaa$”
Approach: The given problem can be solved by storing the frequency of the alphabets in a frequency array and sorting them in descending order. The idea is to multiply the highest frequency with 26, 2nd highest frequency with 25, and so on. Follow the steps below to solve the given problem:
- Initialize an auxiliary array, say frequency that stores the frequency of distinct characters in the string S.
- Traverse the string and at every iteration, if the character ch, then increment the frequency using the following cases:
- Upper Case: increment the value at frequency[ch – ‘A’].
- Lower Case: increment the value at frequency[ch – ‘a’].
- Special Character: continue the loop.
- Sort the array frequency in increasing order.
- Initialize a variable, say sum as 0 to store the value of the string.
- Traverse the array in reverse order using a variable i from index 25 to 0, and at every iteration perform the following steps:
- If the value at frequency[i] is 0, then break the loop.
- Otherwise, multiply the value of frequency[i] with i and add it to the variable sum.
- After the above steps, print the value of the sum as the result.
Below is the implementation of the above approach:
Time Complexity: O(N* log N)
Auxiliary Space: O(26)