Maximum Score From Removing Substrings (LeetCode 1717): Solution and Explanation
Remove "ab" for x points and "ba" for y points as often as you like and return the highest total.
Intuition
Characters other than 'a' and 'b' never take part in a pair and block pairs from forming across them, so only runs of a and b matter.
The two pair types compete for the same letters. In "aba" you can take "ab" or "ba" but not both. Each removal uses one 'a' and one 'b', and taking a pair of one kind can cost at most one pair of the other kind.
So the pricier pair should always win. Remove every copy of it first, including copies that only appear after earlier removals join the pieces, then collect the cheaper pair from what remains.
A stack does the removal in one pass: when the incoming character completes the pair with the top of the stack, pop instead of push. Pieces join automatically because the stack holds the current string.
Approach: Greedy with two stack passes
- Let
firstbe "ab" whenx >= y, otherwise "ba".hiis its value andlothe other value. - Pass 1: for each character
c, if the stack top isfirst[0]andcisfirst[1], pop and addhi. Otherwise pushc. - Pass 2: scan the leftover stack the same way for
second, addingloper pop. - Return the total.
Step-by-step example
s = "cdbcbbaaabab", x = 4, y = 5
- y > x, so remove "ba" (5 points) first and "ab" (4 points) second.
- Push c, d, b, c, b, b. The next 'a' meets 'b' on top: pop, total = 5. The next 'a' again meets 'b': pop, total = 10.
- Push 'a', push 'b'. The last 'a' meets 'b': pop, total = 15. Push the final 'b'. The stack reads "cdbcab".
- Pass 2 looks for "ab": the 'b' after 'a' pops, total = 19. "cdbc" is left.
- The answer is 19.
Code: Python, Java, C++
1class Solution:
2 def maximumGain(self, s: str, x: int, y: int) -> int:
3 if x >= y:
4 first, second, hi, lo = "ab", "ba", x, y
5 else:
6 first, second, hi, lo = "ba", "ab", y, x
7 total = 0
8 stack = []
9 for c in s:
10 if stack and stack[-1] == first[0] and c == first[1]:
11 stack.pop()
12 total += hi
13 else:
14 stack.append(c)
15 rest = []
16 for c in stack:
17 if rest and rest[-1] == second[0] and c == second[1]:
18 rest.pop()
19 total += lo
20 else:
21 rest.append(c)
22 return total1class Solution {
2 public int maximumGain(String s, int x, int y) {
3 char a = 'a', b = 'b';
4 int hi = x, lo = y;
5 if (x < y) {
6 a = 'b'; b = 'a'; hi = y; lo = x;
7 }
8 int total = 0;
9 StringBuilder stack = new StringBuilder();
10 for (char c : s.toCharArray()) {
11 int n = stack.length();
12 if (n > 0 && stack.charAt(n - 1) == a && c == b) {
13 stack.setLength(n - 1);
14 total += hi;
15 } else {
16 stack.append(c);
17 }
18 }
19 StringBuilder rest = new StringBuilder();
20 for (int i = 0; i < stack.length(); i++) {
21 char c = stack.charAt(i);
22 int n = rest.length();
23 if (n > 0 && rest.charAt(n - 1) == b && c == a) {
24 rest.setLength(n - 1);
25 total += lo;
26 } else {
27 rest.append(c);
28 }
29 }
30 return total;
31 }
32}1class Solution {
2public:
3 int maximumGain(string s, int x, int y) {
4 char a = 'a', b = 'b';
5 int hi = x, lo = y;
6 if (x < y) {
7 swap(a, b);
8 swap(hi, lo);
9 }
10 int total = 0;
11 string stack;
12 for (char c : s) {
13 if (!stack.empty() && stack.back() == a && c == b) {
14 stack.pop_back();
15 total += hi;
16 } else {
17 stack.push_back(c);
18 }
19 }
20 string rest;
21 for (char c : stack) {
22 if (!rest.empty() && rest.back() == b && c == a) {
23 rest.pop_back();
24 total += lo;
25 } else {
26 rest.push_back(c);
27 }
28 }
29 return total;
30 }
31};Time and space complexity
O(n)
Each pass pushes and pops every character at most once.
O(n)
The two stacks can hold the whole string when nothing is removable.
Other approaches
Counting without a stack (time O(n), space O(1))
Inside each run of a and b, keep counts of unmatched 'a' and 'b'. Match the pricier pair greedily as characters arrive, and at the end of the run take min(countA, countB) of the cheaper pair.
Repeated string replacement (time O(n^2), space O(n))
Keep deleting the pricier pair with string search until none is left, then do the same for the other. Correct, but each deletion rebuilds the string, so it is O(n^2).
Common mistakes
- Removing whichever pair you see first. In "aba" with y > x, taking "ab" first loses the more valuable "ba".
- Only scanning the original string once without a stack. Removals create new pairs, like "aabb" becoming "ab" after the middle pair goes.
- Running pass 2 on the original string instead of the leftovers of pass 1.
- Swapping the pair but not the points when y > x.
Frequently asked questions
Why is the greedy order optimal?
Any optimal plan removes some number of pricier pairs and some number of cheaper ones. Taking as many pricier pairs as possible lowers the cheaper count by at most the same amount, and each swap trades a cheaper pair for a pricier one, which never loses points.
What happens when x equals y?
Either order gives the same total, since every removal is worth the same and the number of pairs you can take is fixed by the letters. The code picks "ab" first.
Can the score overflow a 32-bit int?
No. At most 5 * 10^4 pairs can be removed and each is worth at most 10^4, so the total stays below 5 * 10^8.