Maximize the String value by assigning values in the range [1, 26] to each character


There are 26 total different alphabets exist in the English language. If we want to change the alphabet characters into numerical values then we need to assign the alphabet, values between 1 to 26 only.

Now, in this problem, we need to Maximize the String value by assigning values in the range [1, 26] to each character. Let us see how we should proceed to solve this problem.

Let’s try to understand this problem with the help of some examples.

Input

s = “blpsBpPtT”

Output

221

Explanation

Here, in this question, to maximize the value of the given string we will assign −

  • 26 to p, P

  • 25 to b, B

  • 24 to t, T

  • 23 to l

  • 22 to s

So the net output will become ((26 * 3) + (25 * 2) + (24 * 2) + (23 * 1) + (22 * 1)) which is equal to 221.

Input

s = “Aa$#&*@!Bsbb”

Output

152

Explanation

Here, in this question, to maximize the value of the given string we will assign −

  • 26 to b, B

  • 25 to a, A

  • 24 to s

  • Rest characters would not get any value i.e. their value is zero

So the net output will become ((26 * 3) + (25 * 2) + (24 * 1)) which is equal to 152.

Problem Explanation

Let’s try to understand the problem and find its solution. In this problem, we are supposed to maximize the value of our string by assigning a value that is ranging from 1 to 26 if the character is an alphabet but if it is not an alphabet, for any other character like ‘$’, ‘#’, ‘&’, etc, we would take the value as zero. For uppercase and lowercase characters we would consider both the same if they are of the same type, that is, ‘p’ and ‘P’ would be taken as similar. We can quickly maximize the number by assigning maximum value to the most frequently appeared alphabet character. There are two ways to store the frequencies in the following article, we will see both options soon.

Approach-1 Using Maps

Algorithm

  • Define a map, say m.

  • Run a loop to store the frequencies of the characters of the given string for both uppercase and lowercase letters in the map

  • Push the frequencies in a vector

  • Sort the vector containing frequencies

  • From the back multiply frequencies with 26, 25, 24, and so on up to 1

  • Add the multiplied values together to get the final answer

Example

The following are implementations of the Map Solution in various programming languages −

#include <bits/stdc++.h>
using namespace std;
// Function to maximize the String value by assigning values in the range [1, 26] to each character
int Helper(string s){
   // Define a map to store the characters in it to count the frequency of each character
   map<int,int>m;
   // Run a loop to initiate the map
   for (int i=0; i<s.size(); i++) {
      char chr=s[i];
      // To store lowercase character
      if (chr >= 'a' && chr <= 'z') {
         m[chr - 'a']++;
      }
      // To store uppercase character
      else if (chr >= 'A' && chr <= 'Z') {
         m[chr - 'A']++;
      }
   }
   vector<int>v;
   // Push the frequencies in the vector
   for(auto a:m) {
      v.push_back(a.second);
   }
   // Sort the frequencies
   sort(v.begin(),v.end());
   // Intialise ans variable
   int ans=0, num=26;
   // Get the answer in accordance with the frequencies and range [1, 26]
   for(int i=v.size()-1; i>=0; i--) {
      // Add the highest frequency with num which is initially set to 26
      ans+=(num*v[i]);
      // Decrement num to move to the next largest frequency
      num--;
   }
   // Return the final output
   return ans;
}
int main(){
   // Give the input string
   string S = "aBAbgha";
   // Call the helper function to maximize the String value by assigning values in the range [1, 26] to each character
   cout << "The maximum string value by assigning values in the range [1, 26] to each character is: "<<Helper(S);
   return 0;
}

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
   public static int Helper(String s) {
      // Define a map to store the characters and their frequencies
      Map<Character, Integer> charFrequency = new HashMap<>();

      // Run a loop to initiate the map
      for (char c : s.toCharArray()) {
         // To store lowercase character
         if (Character.isLetter(c)) {
            char lowercaseChar = Character.toLowerCase(c);
            charFrequency.put(lowercaseChar, charFrequency.getOrDefault(lowercaseChar, 0) + 1);
         }
      }
      // Create a list to store the frequencies
      List<Integer> frequencies = new ArrayList<>(charFrequency.values());

      // Sort the frequencies in ascending order
      Collections.sort(frequencies);

      int ans = 0;
      int num = 26;

      // Calculate the maximum string value by assigning values in the range [1, 26] to each character
      for (int i = frequencies.size() - 1; i >= 0; i--) {
         ans += num * frequencies.get(i);
         num--;
      }
      return ans;
   }
   public static void main(String[] args) {
      // Input string
      String S = "aBAbgha";

      // Call the Helper function to maximize the string value
      int maxValue = Helper(S);

      // Print the maximum string value
      System.out.println("The maximum string value by assigning values in the range [1, 26] to each character is: " + maxValue);
   }
}

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175
def Helper(s):
   # Define a dictionary to store the characters and their frequencies
   char_frequency = {}
   # Run a loop to initiate the map
   for char in s:
      if char.isalpha():
         lowercase_char = char.lower()
         char_frequency[lowercase_char] = char_frequency.get(lowercase_char, 0) + 1
    
   # Create a list to store the frequencies
   frequencies = list(char_frequency.values())
    
   # Sort the frequencies in ascending order
   frequencies.sort()
    
   ans = 0
   num = 26
   # Calculate the maximum string value by assigning values in the range [1, 26] to each character
   for i in range(len(frequencies) - 1, -1, -1):
      ans += num * frequencies[i]
      num -= 1
    
   return ans

# Input string
S = "aBAbgha"

# Call the Helper function to maximize the string value
max_value = Helper(S)

# Print the maximum string value
print("The maximum string value by assigning values in the range [1, 26] to each character is:", max_value)

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175

Complexities for the Above Code

  • Time complexity − O(n*(log(n))); here we are using loops but they will run ‘n’ times, however, the sort function will take (n * log(n)) time to execute so we will take overall complexity of our code as n * log(n).

  • Space complexity − O(26); as there are only 26 different alphabets that exist in the English language.

Approach-2 Using Frequency Vector

Algorithm

  • Define a vector, say v, with size 26 and all initial values as ‘0’

  • Run a loop to store the frequencies of the characters of the given string for both uppercase and lowercase letters in the vector, now called a frequency vector

  • Sort the vector containing frequencies

  • From the back multiply frequencies with 26, 25, 24, and so on up to 1 and break the loop when frequency as ‘0’ has reached

  • Add the multiplied values together to get the final answer

Example

The following are implementations of the above approach in various programming languages. In C++, we are using a vector, in C, Java, and Python, we are using arrays and lists."−

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// Function to maximize the String value by assigning values in the range [1, 26] to each character
int Helper(const char* s){
   // Define an array to store the character frequencies
   int v[26] = {0};

   // Populating the array by iterating through the string
   for (int i = 0; s[i]; i++) {
      char chr = s[i];
      if (chr >= 'a' && chr <= 'z') {
         v[chr - 'a']++;
      } else if (chr >= 'A' && chr <= 'Z') {
         v[chr - 'A']++;
      }
   }

   // Sorting the array in ascending order
   for (int i = 0; i < 26; i++) {
      for (int j = i + 1; j < 26; j++) {
         if (v[i] > v[j]) {
            int temp = v[i];
            v[i] = v[j];
            v[j] = temp;
         }
      }
   }
   int ans = 0;
   int num = 26;

   // Calculating the maximum string value by assigning values in the range [1, 26] to each character
   for (int i = 25; i >= 0; i--) {
      if (v[i] == 0) {
         break;
      } else {
         ans += v[i] * (i + 1);
      }
   }
   return ans;
}
int main(){
   // Giving the input string
   const char* S = "aBAbgha";
   
   // Calling the Helper function to maximize the String value
   printf("The maximum string value by assigning values in the range [1, 26] to each character is: %d\n", Helper(S));   
   return 0;
}

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175
#include <bits/stdc++.h>
using namespace std;
// Function to maximize the String value by assigning values in the range [1, 26] to each character
int Helper(string s){
   // Define a frequency vector of size 26 with initial elements as 0
   vector<int> v(26, 0);
   // Run a loop to initiate the vector
   for (int i=0; i<s.size(); i++) {
      char chr=s[i];
      // To store lowercase character
      if (chr >= 'a' && chr <= 'z') {
         v[chr - 'a']++;
      }
      // To store uppercase character
      else if (chr >= 'A' && chr <= 'Z') {
         v[chr - 'A']++;
      }
   }
   // Sort the vector
   sort(v.begin(), v.end());
   // Intialise answer variable
   int ans = 0;
   // Get the answer in accordance with the frequencies and range [1, 26]
   for (int i = 25; i >= 0; i--) {
      // Check if the value of frequency is 0 or not, if 0 then stop the loop
      if (v[i] == 0) {
         break;
      } else {
         // Add the highest frequency with a number that is initially set to 26
         ans+=v[i] * (i + 1);
      }
   }
   // Return the maximum sum obtained
   return ans;
}
int main(){
   // Give the input string
   string S = "aBAbgha";
   // Call the helper function to maximize the String value by assigning values in the range [1, 26] to each character
   cout << "The maximum string value by assigning values in the range [1, 26] to each character is: "<<Helper(S);
   return 0;
}

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175
public class Main {
   public static int Helper(String s) {
      // Define an array to store the character frequencies
      int[] v = new int[26];

      // Populating the array by iterating through the string
      for (int i = 0; i < s.length(); i++) {
         char chr = s.charAt(i);
         if (chr >= 'a' && chr <= 'z') {
            v[chr - 'a']++;
         } else if (chr >= 'A' && chr <= 'Z') {
            v[chr - 'A']++;
         }
      }

      // Sorting the array in ascending order
      for (int i = 0; i < 26; i++) {
         for (int j = i + 1; j < 26; j++) {
            if (v[i] > v[j]) {
               int temp = v[i];
               v[i] = v[j];
               v[j] = temp;
            }
         }
      }
      int ans = 0;
      int num = 26;
      // Calculating the maximum string value by assigning values in the range [1, 26] to each character
      for (int i = 25; i >= 0; i--) {
         if (v[i] == 0) {
            break;
         } else {
            ans += v[i] * (i + 1);
         }
      }
      return ans;
   }
   public static void main(String[] args) {
      // Giving the input string
      String S = "aBAbgha";

      // Calling the Helper function to maximize the String value
      System.out.println("The maximum string value by assigning values in the range [1, 26] to each character is: " + Helper(S));
   }
}

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175
def Helper(s):
   # Define a list to store the character frequencies
   v = [0] * 26

   # Populating the list by iterating through the string
   for i in range(len(s)):
      chr = s[i]
      if 'a' <= chr <= 'z':
         v[ord(chr) - ord('a')] += 1
      elif 'A' <= chr <= 'Z':
         v[ord(chr) - ord('A')] += 1

   # Sorting the list in ascending order
   v.sort()
   ans = 0
   num = 26
   # Calculating the maximum string value by assigning values in the range [1, 26] to each character
   for i in range(25, -1, -1):
      if v[i] == 0:
         break
      else:
         ans += v[i] * (i + 1)

   return ans

# Giving the input string
S = "aBAbgha"

# Calling the Helper function to maximize the String value
print("The maximum string value by assigning values in the range [1, 26] to each character is:", Helper(S))

Output

The maximum string value by assigning values in the range [1, 26] to each character is: 175

Complexities for the Above Code

  • Time complexity − O(n*(log(n))); here we are using loops but they will run ‘n’ times, however, the sort function will take (n * log(n)) time to execute so we will take overall complexity of our code as n * log(n).

  • Space complexity − O(26); as there are only 26 different alphabets that exist in the English language.

NOTE − The above approach uses a frequency vector instead of storing frequencies in the map.

Conclusion

In this article, to maximize the String value by assigning values in the range [1, 26] to each character we would take up two approaches to store the frequencies of each element. In the first approach, we will use a map to store the frequencies of each alphabet whether the alphabet is in lowercase or uppercase. However, in the second approach, we can avoid the space that the map takes up which is extra space, and can directly use a frequency vector.

Updated on: 05-Feb-2024

105 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements