Maximum Score From Removing Substrings

You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. - Remove substring `"ab"` and gain `x` points. - For example, when removing `"ab"` from `"cabxbae"` it becomes `"cxbae"`. - Remove substring `"ba"` and gain `y` points. - For example, when removing `"ba"` from `"cabxbae"` it becomes `"cabxe"`. Return *the maximum points you can gain after applying the above operations on* `s`.

30:00

Maximum Score From Removing Substrings
medium
Free written solution
Topics
Companies

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

  • Remove substring "ab" and gain x points.
    • For example, when removing "ab" from "cabxbae" it becomes "cxbae".
  • Remove substring "ba" and gain y points.
    • For example, when removing "ba" from "cabxbae" it becomes "cabxe".

Return the maximum points you can gain after applying the above operations on s.

Example 1:
Input: {"s":"cdbcbbaaabab","x":4,"y":5}
Output: 19
Constraints:
  • 1≤s.length≤1051 \leq \text{s.length} \leq 10^5

  • 1≤x,y≤1041 \leq x, y \leq 10^4

  • s consists of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"cdbcbbaaabab","x":4,"y":5}

"ab" is worth x = 4 and "ba" is worth y = 5. Removing one pair can destroy the other kind, so grab the pricier pair "ba" (5 points) everywhere first, then take "ab" (4 points) from what is left.

pass 1

"ba" = 5 pts

pass 2

"ab" = 4 pts

s

c
d
b
c
b
b
a
a
a
b
a
b

left after pass 1

removed "ba"

never removed

removed "ab"

stack (pass 1): 0

empty

0 x 5 = 0

+

0 x 4 = 0

=

total

0

Variables
VariableValue
firstba
hi5
secondab
lo4
DepthFunction Call
Stack empty
0/21