Maximum Score From Removing Substrings - Problem
You're given a string s and two integers x and y representing points you can earn by removing specific substrings. Your goal is to maximize your total points by strategically removing substrings.
Two operations available:
- Remove "ab" - Gain
xpoints - Remove "ba" - Gain
ypoints
Example: In string "cabxbae" with x=5, y=4:
• Remove "ab" → "cxbae" (+5 points)
• Remove "ba" → "cxe" (+4 points)
• Total: 9 points
The key insight is that you should be greedy - always prioritize removing the substring that gives more points first, as this maximizes your total score.
Input & Output
example_1.py — Basic Case
$
Input:
s = "caba", x = 5, y = 4
›
Output:
5
💡 Note:
Remove 'ab' from 'caba' to get 'ca' and gain 5 points. No more 'ab' or 'ba' substrings exist. Total: 5 points.
example_2.py — Multiple Removals
$
Input:
s = "aabbaaxybbaabb", x = 5, y = 4
›
Output:
20
💡 Note:
Remove all 'ab' first (higher value): 4 'ab' substrings × 5 = 20 points. Then check for remaining 'ba' patterns.
example_3.py — Edge Case
$
Input:
s = "aabb", x = 1, y = 2
›
Output:
2
💡 Note:
Since y > x, prioritize 'ba'. Remove 'ba' from middle to get 'ab', then remove 'ab'. Total: 2 + 1 = 3... Wait, that's wrong. Actually: 'aabb' → can only remove 'ab' once for 1 point, then 'ab' again for 1 point = 2 total.
Constraints
- 1 ≤ s.length ≤ 105
- 1 ≤ x, y ≤ 104
- s consists of lowercase English letters only
- Key insight: Greedy approach always works - prioritize higher value first
Visualization
Tap to expand
Understanding the Visualization
1
Choose Strategy
Determine which package type gives more profit ($x for 'ab' vs $y for 'ba')
2
First Production Line
Process conveyor belt, packaging all high-value combinations immediately when possible
3
Second Production Line
Process remaining items for any lower-value packaging opportunities
4
Count Revenue
Sum up all earnings from both production lines for maximum profit
Key Takeaway
🎯 Key Insight: The greedy strategy works because prioritizing higher-value substring removals never prevents us from achieving the optimal solution - there's no benefit to removing lower-value patterns first.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code