Maximum Score From Removing Substrings - Problem

You are given a string s and two integers x and y. You can perform two types of operations any number of times:

Remove substring "ab" and gain x points.
For example, when removing "ab" from "cabxbae" it becomes "cxbae".

Remove substring "ba" and gain y points.
For example, when removing "ba" from "cabxbae" it becomes "cabxe".

Return the maximum points you can gain after applying the above operations on s.

Input & Output

Example 1 — Basic Case
$ Input: s = "caba", x = 2, y = 1
Output: 5
💡 Note: Remove the substring "ab" to get "ca", earning 2 points. Then remove "ba" is not possible. Actually, we should remove "ba" first for 1 point to get "ca", but optimal is: count pairs - we have 1 'a' before 'b' and 1 'a' after 'b', so we can form 1 "ab" pair (2 points) but no "ba" pairs. Wait, let me recalculate: "caba" - we can remove "ab" (positions 1,2) to get "ca" for 2 points, no more pairs possible. Total: 2 points.
Example 2 — Higher Y Value
$ Input: s = "aabb", x = 1, y = 2
Output: 4
💡 Note: Since y > x, prioritize "ba" pairs. Process left to right: 'a','a','b','b'. We can form 2 "ab" pairs for 2 points, or rearrange to form 2 "ba" pairs for 4 points. Using greedy approach with y>x: we get 2 "ab" pairs total = 2×1 = 2 points. Actually optimal: we have 2 a's and 2 b's, so we can make 2 pairs. Since y>x, we want "ba" pairs, but in "aabb" we can only make "ab" pairs directly. Total: 2 points.
Example 3 — No Pairs Possible
$ Input: s = "aaa", x = 3, y = 4
Output: 0
💡 Note: String contains only 'a' characters, so no "ab" or "ba" substrings can be formed. Total score: 0.

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ x, y ≤ 104
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximum Score From Removing SubstringsInput String:"caba"Points:x=2, y=1Operations:Remove "ab" or "ba"Step 1:Find "ab" → +2Step 2:String becomes "ca"Step 3:No more pairsGreedy Strategy:1. Remove higher-value pairs first2. Use stack for efficient pair matchingMaximum Score: 2
Understanding the Visualization
1
Input
String with a's and b's, point values x and y
2
Strategy
Remove higher-value pairs first using greedy approach
3
Output
Maximum total points achievable
Key Takeaway
🎯 Key Insight: Use greedy approach - always remove the more valuable substring type first to maximize total score
Asked in
Google 25 Amazon 18 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
890 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