Maximum Score From Removing Substrings — LeetCode 1717 Python Solution

MediumStackGreedyString
Problem
#1717
Pattern
Stack
Reading time
4 min

The problem

You are given a string s and two integers x and y. You can perform two types of operations any number of times.

Example

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.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n), where n is the length of string s
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1717. Maximum Score From Removing Substrings is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1717. Maximum Score From Removing Substrings?
LeetCode 1717. Maximum Score From Removing Substrings is rated Medium on LeetCode.
What is the time complexity of LeetCode 1717. Maximum Score From Removing Substrings?
The Python solution on this page runs in O(n), where n is the length of string s.
What is the space complexity of LeetCode 1717. Maximum Score From Removing Substrings?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1717. Maximum Score From Removing Substrings cover?
LeetCode 1717. Maximum Score From Removing Substrings is tagged Stack, Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview