Jul 12, 2024
ab and ba)ab = 4, ba = 5ab and ba are of size two.ab) will exist to conflict during the second phase.remove_pairs
remove_pairs twice: first for the higher score pair, then the other.class Solution:
def maximumGain(self, s: str, x: int, y: int) -> int:
def remove_pairs(s, pair, score):
stack = []
total_score = 0
for char in s:
if stack and stack[-1] == pair[0] and char == pair[1]:
stack.pop()
total_score += score
else:
stack.append(char)
return ''.join(stack), total_score
first_pair, second_pair = ('ab', 'ba') if x > y else ('ba', 'ab')
first_score, second_score = (x, y) if x > y else (y, x)
s, first_total = remove_pairs(s, first_pair, first_score)
s, second_total = remove_pairs(s, second_pair, second_score)
return first_total + second_total
remove_pairs: Removes pair from the string and returns the modified string and total score.remove_pairs for both pairs based on their scores.