AlgoInsight

DSA problem

Maximum Score From Removing Substrings

MediumGreedyPattern: Greedytop600AmazonGoogleMicrosoftBloombergApple

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 (only possible if "ab" is a substring of s), or remove substring "ba" and gain y points (only possible if "ba" is a substring of s). Return the maximum points you can gain after applying the above operations on s.

A search over the order of removals is exponential in the number of operations, so brute force is out of the question. The key observation is that within a maximal run of 'a's and 'b's (any letter outside {a, b} acts as a hard barrier), every "ab" removal and every "ba" removal both reduce the count of as and bs by exactly one each. So the only thing that varies between strategies is how many of each removal type we perform.

This gives the greedy structure: always prefer the higher-paying removal type. If x >= y, sweep the string and pop "ab" pairs first; then run a second sweep for "ba". Each sweep is naturally implemented with a stack: push the current character; if the top two characters form the high-paying pattern, pop both and add the points. After exhausting the high-paying pattern, repeat for the low-paying one on the residual string.

This works because once the higher-paying pattern is fully exhausted, no future removal can recreate it inside the same alternating run — the remaining letters all share the same first letter of the second pattern. Total time is O(n) over the two stack sweeps, and total space is O(n) for the stack.

Examples

Example 1
Input: s = "cdbcbbaaabab", x = 4, y = 5
Output: 19
Explanation: Since y > x, prefer "ba" removals first. Remove the "ba" inside ...baaabab to get "cdbcbbaaab" (+5), then continue: another "ba" -> "cdbcbbaab" (+5), one more "ba" -> "cdbcbbb"... after extracting every "ba" then every "ab" the total is 19.
Example 2
Input: s = "aabbaaxybbaabb", x = 5, y = 4
Output: 20
Explanation: Since x > y, prefer "ab" removals first. The 'x' and 'y' act as barriers separating maximal a/b runs. Inside each run, peel "ab" pairs first, then any leftover "ba" pairs, summing to 20.
Example 3
Input: s = "abba", x = 7, y = 7
Output: 14
Explanation: Either pattern pays 7. Remove "bb"? No, only "ab" and "ba". Remove "ab" first -> "ba" -> remove "ba" -> "", or remove "bb" — wait, only ab/ba are allowed. Two removals at 7 each = 14.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

greedystringstack

Browse all DSA problems