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 Cost INPUT String s = "adaa" 'a' idx 0 'd' idx 1 'a' idx 2 'a' idx 3 chars = "d" 'd' vals = [-1000] -1000 Character Values: 'a' = 1 (alphabet pos) 'd' = -1000 (custom) ALGORITHM STEPS 1 Build Value Map Map chars to custom vals 2 Apply Kadane's Algo Max subarray sum approach 3 Track Current Sum Reset if negative 4 Track Max Cost Update global maximum Kadane's Iteration: i=0: 'a'=1 cur=1 max=1 i=1: 'd'=-1000 cur=0 max=1 i=2: 'a'=1 cur=1 max=1 i=3: 'a'=1 cur=2 max=2 max = 2 FINAL RESULT Maximum Cost Substring "aa" Substring at indices [2,3] Cost Calculation: 'a' + 'a' = 1 + 1 = 2 Output: 2 OK - Maximum achieved! Key Insight: This problem transforms into Kadane's Maximum Subarray Sum algorithm. First, convert each character to its value (custom from vals[] or default alphabet position). Then apply Kadane's algorithm: curSum = max(0, curSum + val[i]); maxSum = max(maxSum, curSum); -- Time: O(n), Space: O(1) TutorialsPoint - Find the Substring With Maximum Cost | Optimal Solution (Kadane's Algorithm)
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