VOOZH about

URL: https://www.geeksforgeeks.org/dsa/substring-with-maximum-ascii-sum-when-some-ascii-values-are-redefined/

⇱ Substring with maximum ASCII sum when some ASCII values are redefined - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Substring with maximum ASCII sum when some ASCII values are redefined

Last Updated : 23 Jul, 2025

Given a string W, and two arrays X[] and B[] of size N each where the ASCII value of character X[i] is redefined to B[i]. Find the substring with the maximum sum of the ASCII (American Standard Code for Information Interchange) value of the characters.

Note: Uppercase & lowercase both will be present in the string W.

Input: W = "abcde", N = 1, X[] = { 'c' }, B[] = { -1000 }
Output: de
Explanation: Substring "de" has the maximum sum of ascii value, including c decreases the sum value

Input: W = "dbfbsdbf", N = 2, X[] = { 'b', 's' }, B[] = { -100, 45  }
Output: dbfbsdbf
Explanation: Substring "dbfbsdbf" has the maximum sum of ascii values.

Approach- This can be solved using the following idea:

Keep a map(ordered or unordered) where we can store the redefined ASCII values of characters that are provided in array X, Now use Kadane's algorithm to find the maximum substring sum with redefined ASCII values of characters.

Follow the steps mentioned below to solve the problem:

  • Take two empty strings ans="" and res ="".
  • If the size of the given string is 1, return the original string as it will be the only maximum string.
  • Take an unordered map and store redefined ASCII values in that map.
  • Traverse the string and increase the sum every time by ASCII value of the character(predefined or redefined) and store the string in 'ans' till the sum is greater than zero.
  • If the sum becomes negative, clear the string 'ans' and put sum = 0 again.
  • Every time check whether the sum is greater than the maximum or not.
  • If the sum is greater than the maximum, update maximum = sum and res = ans.
  • Return res as the required answer.

Below is the implementation of the above approach:


Output
de

Time Complexity: O(|W|) where|W| is the length of the string
Auxiliary Space: O(N)

Comment
Article Tags:
Article Tags: