All problems
1115MediumStringStackGreedy

Pulling Pairs Off the Tape

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1717Maximum Score From Removing Substrings

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A tape tape holds lowercase letters. Two moves are allowed, each usable as often as the pattern shows up:

  • Pull out a neighbouring pair reading ab and collect x points.
  • Pull out a neighbouring pair reading ba and collect y points.

Pulling a pair out closes the gap, so letters that were apart may become neighbours.

Return the most points that can be collected.

Examples

Example 1

Input
tape = "aba", x = 1, y = 5
Output
5

Only one pull is ever possible. Taking ba from the back pays 5, while taking ab from the front would pay 1.

Example 2

Input
tape = "bbba", x = 5, y = 1
Output
1

The only pair on offer reads ba and pays 1. Once it is gone the tape reads bb with nothing left to pull.

Example 3

Input
tape = "abcba", x = 5, y = 1
Output
6

The c splits the tape in two. On the left ab pays 5 and on the right ba pays 1.

Constraints

  • 1 <= tape.length <= 10^5
  • 1 <= x <= 10^4
  • 1 <= y <= 10^4
  • tape holds only lowercase English letters

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def maximum_gain(tape: str, x: int, y: int) -> int:
Java
public int maximumGain(String tape, int x, int y)
September 7
Apply