Minimize ASCII values sum after removing all occurrences of one character in C++


Suppose we have a string. We have to minimize the sum of ASCII values, of each character to the string, after removing every occurrence of a particular character. Suppose a string is given like “hello” the sum of ASCII characters is (104 + 101 + 108 + 108 + 111) = 532. Now check occurrences of each characters.

  • h has occurred one time, so cost is 1 * 104 = 104
  • e has occurred one time, so cost is 1 * 101 = 101
  • l has occurred one time, so cost is 2 * 108 = 216
  • o has occurred one time, so cost is 1 * 111 = 111

Here l has occurred maximum amount of time, so if we remove all occurrences of l, then the value will be minimized. So actually we are removing the max value from the above list. Here the final result will be 532 – 216 = 316

The logic is simple at first we have to take the ASCII sum of the string. Then count the frequency of each character present in the string, then remove that character which is contributing max value as occurrence * ASCII value. The subtracted value is the result.

Example

#include <iostream>
using namespace std;
int minASCIISum(string str, int len) {
   int max_val = INT_MIN, sum = 0;
   int frequency[26] = { 0 };
   for (int i = 0; i < len; i++) {
      frequency[str[i] - 'a']++;
      sum += (int)str[i];
   }
   for (int i = 0; i < 26; i++)
   max_val = max(max_val, frequency[i] * (i + 'a'));
   return (sum - max_val);
}
int main() {
   string str = "hello";
   int n = str.length();
   cout << "Minimized Sum: " << minASCIISum(str, n);
}

Output

Minimized Sum: 316

Updated on: 21-Oct-2019

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements