Maximum Score From Removing Substrings

Medium Topics Company Tags

Starting with the lowercase string s, repeatedly remove adjacent ab for x points or adjacent ba for y points. The characters on either side of a removed pair become adjacent, so later removals may become possible. You may choose the operations in any order and stop at any time. Return the largest total score you can earn.

Example 1:

Input: s = "abba"
x = 7
y = 3

Output: 10

Explanation: Remove the initial ab for 7 points, leaving ba. Remove that pair for 3 more points. Both pairs are removed and the total is 10.

Example 2:

Input: s = "baba"
x = 2
y = 6

Output: 12

Explanation: Remove each ba for 6 points, earning 12. Removing the middle ab first would earn only 2 and leave one ba, for a smaller total of 8.

Example 3:

Input: s = "acb"
x = 5
y = 9

Output: 0

Explanation: The a and b are separated by c. Neither removable pair occurs, so no operation is possible and the score is 0.

Constraints:

  • 1 <= s.length <= 100000
  • s contains only lowercase English letters.
  • 1 <= x, y <= 10000


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.