Substring with maximum ASCII sum when some ASCII values are redefined
Last Updated :
08 Feb, 2024
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:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find maximum sum string.
string maxSum(string w, char x[], int b[], int n)
{
string ans = "", res = "";
// If Length of the given string is 1
// we can return the string.
// It will be maximum in itself
if (w.length() == 1)
return w;
long long maxi = INT_MIN, sum = 0, s = 0;
unordered_map<char, int> mp;
// Taking unordered_map to store
// new ascii value of character in x[].
for (int i = 0; i < n; i++) {
mp[x[i]] = b[i];
}
// Traversing through the string .
for (int i = 0; i < w.length(); i++) {
// Store the string in ans.
ans += w[i];
string temp;
// If we find any redefined value of char
// of string w, we will add that value
// to the sum else add it's predefined value
if (mp.find(w[i]) == mp.end()) {
sum += w[i];
}
else {
sum += mp[w[i]];
}
// If anytime we find sum is getting negative
// clear the values stored in "ans"
// and make sum=0 again
if (sum < 0) {
sum = 0;
ans.clear();
}
// If sum is greater than maximum
// maxi will be updated as sum and
// new result would be string stored in ans
if (sum > maxi) {
maxi = sum;
res = ans;
}
}
return res;
}
// Driver code
int main()
{
string W = "abcde";
int N = 1;
char X[N] = { 'c' };
int B[N] = { -1000 };
// Function call
cout << maxSum(W, X, B, N) << endl;
return 0;
}
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG {
// Function to find maximum sum string
static String maxSum(String w, char[] x, int[] b, int n)
{
String ans = "", res = "";
// If Length of the given string is 1
// we can return the string.
// It will be maximum in itself
if (w.length() == 1) {
return w;
}
int maxi = Integer.MIN_VALUE, sum = 0, s = 0;
HashMap<Character, Integer> mp = new HashMap<>();
// Taking unordered_map to store
// new ascii value of character in x[].
for (int i = 0; i < n; i++) {
mp.put(x[i], b[i]);
}
// Traversing through the string.
for (int i = 0; i < w.length(); i++) {
// Store the string in ans.
ans += w.charAt(i);
String temp = "";
// If we find any redefined value of char
// of string w, we will add that value
// to the sum else add it's predefined value
if (!mp.containsKey(w.charAt(i))) {
sum += w.charAt(i);
}
else {
sum += mp.get(w.charAt(i));
}
// If anytime we find sum is getting negative
// clear the values stored in "ans"
// and make sum=0 again
if (sum < 0) {
sum = 0;
ans = "";
}
// If sum is greater than maximum
// maxi will be updated as sum and
// new result would be string stored in ans
if (sum > maxi) {
maxi = sum;
res = ans;
}
}
return res;
}
public static void main(String[] args)
{
String W = "abcde";
int N = 1;
char[] X = { 'c' };
int[] B = { -1000 };
// Function call
System.out.println(maxSum(W, X, B, N));
}
}
// This code is contributed by lokeshmvs21.
Python3
# Python code to implement the approach
import sys
# Function to find maximum sum string.
def maxSum(w, x, b, n):
ans = ""
res = ""
# If Length of the given string is 1
# we can return the string.
# It will be maximum in itself
if(len(w) == 1):
return w
maxi = -1*sys.maxsize
sum, s = 0, 0
mp = dict()
# Taking unordered_map to store
# new ascii value of character in x[].
for i in range(n):
mp[x[i]] = b[i]
# Traversing through the string .
for i in range(len(w)):
# Store the string in ans.
ans = ans + w[i]
temp=""
# If we find any redefined value of char
# of string w, we will add that value
# to the sum else add it's predefined value
if w[i] in mp.keys():
sum = sum + mp[w[i]]
else:
sum = sum + ord(w[i])
# If anytime we find sum is getting negative
# clear the values stored in "ans"
# and make sum=0 again
if(sum < 0):
sum = 0
ans = ""
# If sum is greater than maximum
# maxi will be updated as sum and
# new result would be string stored in ans
if(sum > maxi):
maxi = sum
res = ans
return res
# Driver code
W ="abcde"
N = 1
X = ['c']
B = [-1000]
# Function call
print(maxSum(W, X, B, N))
# This code is contributed by Pushpesh Raj.
C#
using System;
using System.Collections.Generic;
public class GFG {
// Function to find maximum sum string.
public static string maxSum(string w, char[] x, int[] b,
int n)
{
string ans = "", res = "";
// If Length of the given string is 1
// we can return the string.
// It will be maximum in itself
if (w.Length == 1)
return w;
long maxi = Int32.MinValue;
long sum = 0;
long longE = 0;
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Taking unordered_map to store
// new ascii value of character in x[].
for (int i = 0; i < 26; i++) {
mp[i] = 0;
}
for (int i = 0; i < n; i++) {
mp[x[i] - 'a'] = b[i];
}
// Traversing through the string .
for (int i = 0; i < w.Length; i++) {
// Store the string in ans.
ans += w[i];
string temp;
// If we find any redefined value of char
// of string w, we will add that value
// to the sum else add it's predefined value
if (mp[w[i] - 'a'] == 0) {
sum += w[i];
}
else {
sum += mp[w[i] - 'a'];
}
// If anytime we find sum is getting negative
// clear the values stored in "ans"
// and make sum=0 again
if (sum < 0) {
sum = 0;
ans = "";
}
// If sum is greater than maximum
// maxi will be updated as sum and
// new result would be string stored in ans
if (sum > maxi) {
maxi = sum;
res = ans;
}
}
return res;
}
public static void Main()
{
// Code
string W = "abcde";
int N = 1;
char[] X = { 'c' };
int[] B = { -1000 };
// Function call
Console.WriteLine(maxSum(W, X, B, N));
}
}
// This code is contributed by akashish__
JavaScript
// JavaScript code for the above approach
// Function to find maximum sum string.
function maxSum(w, x, b, n) {
let ans = "", res = "";
// If Length of the given string is 1
// we can return the string.
// It will be maximum in itself
if (w.length == 1)
return w;
let maxi = Number.MIN_VALUE, sum = 0, s = 0;
let mp = new Map();
// Taking unordered_map to store
// new ascii value of character in x[].
for (let i = 0; i < n; i++) {
mp.set(x[i], b[i]);
}
// Traversing through the string .
for (let i = 0; i < w.length; i++) {
// Store the string in ans.
ans += w[i];
let temp;
// If we find any redefined value of char
// of string w, we will add that value
// to the sum else add it's predefined value
if (!mp.has(w[i])) {
sum += w[i].charCodeAt(0);
}
else {
sum += mp.get(w[i]);
}
// If anytime we find sum is getting negative
// clear the values stored in "ans"
// and make sum=0 again
if (sum < 0) {
sum = 0;
ans = "";
}
// If sum is greater than maximum
// maxi will be updated as sum and
// new result would be string stored in ans
if (sum > maxi) {
maxi = sum;
res = ans;
}
}
return res;
}
// Driver code
let W = "abcde";
let N = 1;
let X = ['c'];
let B = [-1000];
// Function call
console.log(maxSum(W, X, B, N) + "<br>");
// This code is contributed by Potta Lokesh
Time Complexity: O(|W|) where|W| is the length of the string
Auxiliary Space: O(N)
Similar Reads
Remove k characters in a String such that ASCII sum is minimum Given a string s and an integer k, the task is to remove k characters from the string such that the sum of ASCII (American Standard Code for Information Interchange) values of the remaining characters is minimized. Examples: Input: s = "ABbc", k = 2Output: 131Explanation: We need to remove exactly 2
7 min read
Find the Substring with maximum product Given string str containing only lowercase English alphabets of size N, the task is to find the substring having the maximum product. Each English alphabet has a value such that val('a') = 0, val('b') = 1, val('c') = 2, ......, val('z') = 25. Examples: Input: str = "sdtfakdhdahdzz" Output: hdzz Here
5 min read
Arrange a binary string to get maximum value within a range of indices Given a string consisting of only 0's and 1's. Now you are given N non-intersecting ranges L, R ( L <= R), more specifically [L1, R1], [L2, R2], ..., [LN, RN], No two of these intervals overlap â formally, for each valid i, j such that i!=j, either Ri<Lj or Rj<Li. The task is to find a vali
8 min read
Split a String into two Substring such that the sum of unique characters is maximum Given a string str, the task is to partition the string into two substrings such that the sum of unique characters of both substrings is the maximum possible. Examples: Input: str = "abcabcdâ Output: 7Explanation: Partition the given string into "abc" and "abcd", the sum of unique characters is 3 +
14 min read
Minimize ASCII values sum after removing all occurrences of one character Given string str, the task is to minimize the sum of ASCII values of each character of str after removing every occurrence of a particular character. Examples: Input: str = "geeksforgeeks" Output: 977 'g' occurs twice -> 2 * 103 = 206 'e' occurs 4 times -> 4 * 101 = 404 'k' occurs twice ->
8 min read
Find heaviest increasing Subsequence with maximum sum in a String Given a string s and an array arr[] representing the weights of each character in the string, the task is to find the heaviest increasing subsequence with the maximum sum and return that subsequence. Examples: Input: s = "acbde", arr[] = {2, 4, 3, 5, 1}Output: acdExplanation: The heaviest increasing
8 min read