Find the Substring With Maximum Cost - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "adaa", chars = "d", vals = [-1000]
Output: 2
💡 Note: Character 'd' has value -1000, others use alphabet positions: 'a'=1. Best substring is "aa" at the end with cost 1+1=2.
Example 2 — All Custom Values
$ Input: s = "abc", chars = "abc", vals = [-1,-1,1]
Output: 1
💡 Note: All characters have custom values: 'a'=-1, 'b'=-1, 'c'=1. Best substring is "c" with cost 1.
Example 3 — Empty Substring Optimal
$ Input: s = "z", chars = "z", vals = [-100]
Output: 0
💡 Note: Character 'z' has value -100, which is negative. Empty substring has cost 0, which is better.

Constraints

  • 1 ≤ s.length ≤ 105
  • 0 ≤ chars.length ≤ 26
  • chars.length = vals.length
  • 1 ≤ vals[i] ≤ 2000
  • s and chars consist of lowercase English letters
  • All characters in chars are distinct

Visualization

Tap to expand
Find the Substring With Maximum CostInput: s = "adaa", chars = "d", vals = [-1000]adaa↓ Transform to values ↓1-100011Apply Kadane's Algorithm → Best substring: "aa"Maximum Cost: 2
Understanding the Visualization
1
Input
String s with custom character values
2
Transform
Convert characters to their corresponding values
3
Apply Kadane's
Find maximum sum contiguous subarray
Key Takeaway
🎯 Key Insight: Convert string to values array, then use Kadane's algorithm for maximum subarray sum
Asked in
Google 12 Facebook 8 Amazon 15 Microsoft 6
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen