#1717

Maximum Score From Removing Substrings

Medium
StringStackGreedyStackGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a stack to efficiently manage the removal of 'ab' and 'ba' substrings while keeping track of the score. This approach ensures that we only traverse the string once, making it much faster.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a stack to keep track of characters and a score variable to 0.
  2. 2Step 2: Iterate through each character in the string.
  3. 3Step 3: For each character, check the top of the stack. If it forms 'ab' or 'ba' with the current character, pop from the stack and update the score accordingly.
  4. 4Step 4: If it doesn't form a substring, push the current character onto the stack.
  5. 5Step 5: Continue until all characters are processed.
solution.py16 lines
1# Full working Python code
2
3def maxScore(s: str, x: int, y: int) -> int:
4    stack = []
5    score = 0
6    for char in s:
7        if stack and ((stack[-1] == 'a' and char == 'b') or (stack[-1] == 'b' and char == 'a')):
8            if stack[-1] == 'a':
9                stack.pop()
10                score += x
11            else:
12                stack.pop()
13                score += y
14        else:
15            stack.append(char)
16    return score

Complexity note: This complexity is due to a single pass through the string, where each character is pushed or popped from the stack at most once.

  • 1Removing 'ab' or 'ba' can be done in any order, but the score gained from each operation differs.
  • 2Using a stack allows us to efficiently manage the removal of substrings while keeping track of the score.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.