[LeetCode] Find the Substring With Maximum Cost

2606. Find the Substring With Maximum Cost

You are given a string s, a string chars of distinct characters and an integer array vals of the same length as chars.

The cost of the substring is the sum of the values of each character in the substring. The cost of an empty string is considered 0.

The value of the character is defined in the following way:

  • If the character is not in the string chars, then its value is its corresponding position (1-indexed) in the alphabet.

    • For example, the value of 'a' is 1, the value of 'b' is 2, and so on. The value of 'z' is 26.
  • Otherwise, assuming i is the index where the character occurs in the string chars, then its value is vals[i].

Return the maximum cost among all substrings of the string s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

class Solution {
public:
int maximumCostSubstring(string s, string chars, vector<int>& vals) {
int mi = 0, now = 0, res = 0;
unordered_map<char, int> sc;
for(char ch = 'a'; ch <= 'z'; ch++) {
sc[ch] = ch - 'a' + 1;
}
for(int i = 0; i < chars.size(); i++) sc[chars[i]] = vals[i];
for(int i = 0; i < s.length(); i++) {
now += sc[s[i]];
res = max(res, now - mi);
mi = min(mi, now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/02/PS/LeetCode/find-the-substring-with-maximum-cost/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.