Problem Description
Given a string s, a string chars that contains distinct characters, and an integer array vals of the same length as chars, determine the maximum cost among all substrings of s. The cost of a substring is defined as the sum of the values of its characters. For any character in s, if it exists in chars, its value is given by vals at the corresponding index; otherwise, its value is its alphabetical position (1-indexed). The cost of an empty substring is 0.
Key Insights
- Build a hash map of custom values for characters present in chars.
- For characters not in the hash map, compute their value using their alphabetical position.
- Convert the problem into finding the maximum subarray sum on the array of computed character values.
- Kadane's algorithm is an optimal approach for this maximum subarray sum problem.
- The result should never be negative since the empty substring (cost 0) is always a valid option.
Space and Time Complexity
Time Complexity: O(n), where n is the length of s.
Space Complexity: O(1) additional space (the custom mapping is of constant size due to the limited alphabet).
Solution
The solution involves mapping the characters in chars to their corresponding values using a hash map. As we iterate over string s, we determine each character's value, then apply Kadane's algorithm to find the contiguous substring (subarray) that gives the maximum sum. The algorithm resets the current sum whenever it falls below the current character's value, effectively starting a new substring calculation. This approach efficiently yields the maximum possible cost among all substrings.