Maximum Score From Removing Substrings Problem
Description
LeetCode Problem 1717.
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 gainxpoints.- For example, when removing
"ab"from"cabxbae"it becomes"cxbae".
- For example, when removing
- Remove substring
"ba"and gainypoints.- For example, when removing
"ba"from"cabxbae"it becomes"cabxe".
- For example, when removing
Return the maximum points you can gain after applying the above operations on s.
Example 1:
Input: s = "cdbcbbaaabab", x = 4, y = 5
Output: 19
Explanation:
- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.
Total score = 5 + 4 + 5 + 5 = 19.
Example 2:
Input: s = "aabbaaxybbaabb", x = 5, y = 4
Output: 20
Constraints:
1 <= s.length <= 10^51 <= x, y <= 10^4sconsists of lowercase English letters.
Solution
Approach: Greedy
Assume removing "ab" is worth at least as much as removing "ba" (x >= y). If not, swap the roles of a and b and swap x and y.
Any letter other than a or b splits the string into independent pieces that contain only as and bs. In such a piece, every removal takes one a and one b, and in the end only one kind of letter is left, so the number of removals is fixed. To get the most points we greedily remove as many "ab" as possible first, and then remove "ba" with what is left.
Scan the string with two counters, cnt1 for unmatched as and cnt2 for unmatched bs:
- On
a: increasecnt1(it may form"ab"with a laterb). - On
b: ifcnt1 > 0, remove an"ab", decreasecnt1and gainx; otherwise increasecnt2. - On any other letter: the piece ends. The leftover letters form
min(cnt1, cnt2)pairs"ba", worthyeach. Reset both counters.
After the scan, add the "ba" pairs of the last piece.
Complexity: O(n) time and O(1) space, where n is the length of s.
class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
a, b = "a", "b"
if x < y:
x, y = y, x
a, b = b, a
ans = cnt1 = cnt2 = 0
for c in s:
if c == a:
cnt1 += 1
elif c == b:
if cnt1:
ans += x
cnt1 -= 1
else:
cnt2 += 1
else:
ans += min(cnt1, cnt2) * y
cnt1 = cnt2 = 0
ans += min(cnt1, cnt2) * y
return ans