Find the Substring With Maximum Cost - Problem
You're a treasure hunter exploring an ancient string of mysterious characters! Each character has a special value that contributes to your treasure's worth.
Given:
- A string
scontaining the characters you've discovered - A string
charsof distinct special characters with custom values - An integer array
valswherevals[i]is the value ofchars[i]
Character Values:
- If a character appears in
chars, its value is the corresponding value invals - Otherwise, its value is its alphabetical position (a=1, b=2, ..., z=26)
Goal: Find the contiguous substring with the maximum total cost. The cost of a substring is the sum of all its character values.
Example: If s="abc", chars="a", vals=[5], then 'a'=5, 'b'=2, 'c'=3. The substring "a" has cost 5, which might be the maximum!
Input & Output
example_1.py โ Basic Case
$
Input:
s = "adaa", chars = "d", vals = [-1000]
โบ
Output:
2
๐ก Note:
Character values: a=1, d=-1000. The substring "a" (last character) has cost 1. Other options: "aa"=2 (optimal), "ada"=1+(-1000)+1=-998, etc. Maximum cost is 2.
example_2.py โ All Custom Values
$
Input:
s = "abc", chars = "abc", vals = [-1, -1, -1]
โบ
Output:
-1
๐ก Note:
All characters have custom value -1. Since we must choose at least one character (empty substring not allowed for this interpretation), the maximum cost is -1 from any single character substring.
example_3.py โ Mixed Values
$
Input:
s = "xyz", chars = "x", vals = [100]
โบ
Output:
100
๐ก Note:
Character values: x=100, y=25, z=26. The substring "x" gives cost 100, which is greater than "xyz"=100+25+26=151? No wait, "xyz" gives 151 total. Actually the maximum is the full string with cost 151.
Constraints
- 1 โค s.length โค 105
- 0 โค chars.length โค 26
- chars.length == vals.length
- 1 โค |vals[i]| โค 2000
- chars consists of distinct lowercase English letters
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Map the Treasures
First, identify the value of each section - some have special treasures (custom vals), others have standard gems (a=1, b=2, ...)
2
Start the Journey
Begin with the first section and decide: should I continue collecting or start fresh at each step?
3
Make Smart Decisions
If my current collection plus the next section is worth less than just the next section alone, abandon what I have and start fresh
4
Track the Best
Always remember the most valuable collection seen so far - this is your answer!
Key Takeaway
๐ฏ Key Insight: The Maximum Substring Cost problem is really about finding the optimal contiguous subarray sum - Kadane's algorithm solves this elegantly by deciding at each step whether to extend the current path or start anew!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code