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: 2
💡 Note: Remove the substring "ab" at positions 1-2 to get "ca", earning 2 points. No more "ab" or "ba" pairs can be formed. Total score: 2.
Example 2 — Higher Y Value
$ Input: s = "aabb", x = 1, y = 2
Output: 2
💡 Note: Since y > x, we prioritize "ba" pairs, but "aabb" contains no "ba" substrings. We can form 2 "ab" pairs for 2×1 = 2 points total.
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 Substrings INPUT String s: c a b a 0 1 2 3 Input Values: s = "caba" x = 2 (for "ab") y = 1 (for "ba") Operations: Remove "ab" --> +2 pts Remove "ba" --> +1 pt Goal: Maximize total ALGORITHM STEPS 1 Compare x and y x=2 > y=1, so "ab" first 2 Find "ab" in "caba" Found at index 1-2 c ab a +2 3 Remove "ab" --> "ca" Score: 2 c a No more "ab" 4 Now check for "ba" No "ba" in "ca" Wait! Original "caba": "ab" at pos 1 --> +2 --> "ca" Total possibilities = 5 FINAL RESULT Greedy Execution: Start: "caba" 1. Remove "ab" (pos 1-2) +2 Result: "ca" 2. Check "ba" in "ca" none But wait - "caba" has "ba" at pos 2-3 too! +1 Optimal: Remove "ab" first "c[ab]a" --> "ca" (+2) Then "ba" from remain (+1) Maximum Score: 5 2 + 2 + 1 = 5 points Key Insight: The greedy approach works because removing the higher-value substring first maximizes total score. If x >= y, prioritize removing all "ab" first using a stack, then remove all "ba" from remaining. Time: O(n), Space: O(n) for the stack. Each character is pushed/popped at most once. TutorialsPoint - Maximum Score From Removing Substrings | Greedy Approach
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