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 x points
  • Remove "ba" - Gain y points

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
🍭 Candy Factory Assembly LineConveyor Belt: c-a-b-acabaProduction Line 1: ab packages ($5 each)ab→ $5Remaining: caProduction Line 2: ba packages ($4 each)No ba patterns in "ca"→ $0💰 Total Profit: $5Strategy: Always prioritize higher-value packages first!🎯 Key Insight: Greedy approach guarantees maximum profitProcessing high-value combinations first never blocks optimal solutionsTime: O(n) - Single pass per production line | Space: O(n) - Stack storage
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.
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.4K Views
High Frequency
~18 min Avg. Time
1.8K 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