Problem 1717

Abstract / Summary

Remove occurrences of "ab" or "ba" from a string to get the highest possible score by adding 1 for each removal.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1717.py

class Solution:
    def maximumGain(self, s: str, x: int, y: int) -> int:
        result = 0

        # remove the pattern, return score and cleaned up text
        def match(text, a, b, score):
            # basic check to avoid only a or only b
            same = sum(text)
            if same == 0 or same == len(text):
                return ( 0, text )

            result = 0
            seen   = [] # stack
            for c in text:
                #if seen and seen[-1] == a and c == b:
                if c == b and seen and seen[-1] == a:
                    result += score
                    seen.pop()
                else:
                    seen.append(c)
            return ( result, seen )

        def score(segment):
            # process the higher-valued substring first
            if x >= y:
                ab, next = match(segment, 0, 1, x) # "ab"
                ba, _    = match(next,    1, 0, y) # "ba"
            else:
                ba, next = match(segment, 1, 0, y) # "ba"
                ab, _    = match(next,    0, 1, x) # "ab"

            return ab + ba

        # split into segments only consisting of a and b
        have = []
        for c in s + "!": # stop marker so that the final segment is properly handled, too
            if c in "ab":
                have.append(0 if c == "a" else 1)
            elif have:
                result += score(have)
                have    = []

        return result
43 lines | 1495 bytes | submitted May 24, 2024 | GitHub   34% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 66% (300k+ submissions).

Typical patterns to solve this problem:
  • Greedy
  • Stack
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method maximumGain that computes the highest possible total score obtainable by repeatedly deleting the substrings "ab" and "ba" from an input string s. Each deletion of "ab" contributes x points, while each deletion of "ba" contributes y points. The algorithm strategically chooses the order of deletions to maximize the accumulated score.

Core Logic

The method begins by initializing a running total result to zero. It then defines a helper function match that scans a list of encoded characters, removes occurrences of a specific two-character pattern, and returns both the score earned from those removals and the remaining characters.

def match(text, a, b, score):
    same = sum(text)
    if same == 0 or same == len(text):
        return (0, text)

    result = 0
    seen = []                     # stack of characters
    for c in text:
        if c == b and seen and seen[-1] == a:
            result += score
            seen.pop()
        else:
            seen.append(c)
    return (result, seen)

The match function first checks whether the segment consists entirely of one character (all a or all b). In such a case no pattern can be formed, and it returns immediately with zero score and the original segment. Otherwise it iterates through the characters, using a stack (seen) to detect the target pattern a followed by b. When the pattern is found, the score is added and the preceding character is removed from the stack, effectively deleting the substring.

A second helper, score, decides which pattern to eliminate first based on the relative values of x and y. By processing the higher-valued pattern before the lower-valued one, the algorithm ensures that the most profitable deletions are performed whenever possible.

def score(segment):
    if x >= y:
        ab, next = match(segment, 0, 1, x)   # remove "ab" first
        ba, _    = match(next,    1, 0, y)   # then remove "ba"
    else:
        ba, next = match(segment, 1, 0, y)   # remove "ba" first
        ab, _    = match(next,    0, 1, x)   # then remove "ab"
    return ab + ba

The main loop walks through the original string s while appending a sentinel character "!" to guarantee that the final segment is processed. Characters 'a' and 'b' are encoded as 0 and 1 respectively and accumulated in the list have. When a character outside "ab" is encountered, the accumulated segment is handed to score, its contribution is added to result, and the accumulator is cleared.

have = []
for c in s + "!":                     # sentinel ensures final segment handling
    if c in "ab":
        have.append(0 if c == "a" else 1)
    elif have:
        result += score(have)
        have = []

Finally, the method returns the accumulated result.

Edge Cases Handled

The algorithm explicitly checks for segments that contain only one type of character. In such segments the sum of the encoded list is either zero (all 'a') or equal to the length of the list (all 'b'). The early return in match prevents unnecessary stack operations when no deletions are possible.

The sentinel character "!" appended to the input string guarantees that a trailing segment consisting solely of 'a' and 'b' is evaluated even if the original string ends with those characters. Without this marker the final segment could be left unprocessed.

When the input string contains characters other than 'a' and 'b', the loop treats each non-'a'/'b' character as a delimiter, causing any preceding segment to be scored before moving on. This behavior correctly isolates independent blocks of 'a' and 'b' characters, ensuring that deletions do not cross delimiters.

If x and y are equal, the conditional in score defaults to processing "ab" first, but the overall result remains optimal because both patterns yield the same contribution.

Performance Optimizations

The implementation encodes characters as integers (0 for 'a', 1 for 'b') which reduces the overhead of string comparisons inside the inner loop of match. The stack-based approach enables each character to be examined exactly once, achieving linear traversal of each segment.

By deciding the order of pattern removal based on the relative values of x and y, the algorithm avoids a second pass that would be required if both patterns were removed indiscriminately. This ordering ensures that the most valuable deletions are captured early, preventing the need for backtracking or recomputation.

The early exit condition in match that detects homogeneous segments eliminates the stack allocation and iteration for those cases, saving work when large blocks of a single character appear.

Appending a sentinel character eliminates the need for a separate post-loop check to process the last accumulated segment, thereby simplifying control flow and avoiding an extra conditional branch.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long row of magical letter blocks. Some are labeled a and some are labeled b. You want to take away pairs of these blocks to earn points. If you see the letters a and b sitting right next to each other in a special order, you can snap them out of the line and put them in a box to get a treat.

The code looks at all the letters in your long line. It first figures out which pair is worth more points. If the ab pair is worth more, it walks down the line like a little scout looking for every a followed by a b. Every time it finds that specific pair, it grabs them, sets them aside, and adds those points to your pile.

After it finishes hunting for the most valuable pair, it looks at the leftovers. It checks what is still sitting there and goes hunting for the second kind of pair, like ba. It carefully watches the line and repeats the same trick of finding, grabbing, and collecting more points.

To make sure the work gets done properly, the code holds onto the letters it has not used yet in a small pile called a stack. Think of this like a tower of blocks. Whenever it sees a new letter, it checks if the letter right at the top of the tower helps make the special pair it is looking for. If it matches, off they go together. If it does not match, the code puts the new letter on top of the tower to wait for a better friend to come along. It does these steps over and over again until there are no more pairs to find in the entire row of blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 5.89 | σ = 1.79

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Python C# Go Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
haoel C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
haoel C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
28 links | 14 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 solutions   May 24, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality