Skip to main content
impol.dev

Maximum Score From Removing Substrings

Medium

You receive 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 "c ab xbae" it becomes "cxbae".
  • Remove substring "ba" and gain y points.

    • For example, when removing "ba" from "cabx ba e" it becomes "cabxe".

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

Example 1

Input: s = "cdbcbbaaabab", x = 4, y = 5

Output: 19

Explanation:

  • Remove the "ba" highlighted in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.

  • Remove the "ab" highlighted in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.

  • Remove the "ba" highlighted in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.

  • Remove the "ba" highlighted in "cdbcba". Now, s = "cdbc" and 5 points are added to the score.

Total score = 5 + 4 + 5 + 5 = 19.

Example 2

Input: s = "aabbaaxybbaabb", x = 5, y = 4

Output: 20

Constraints

  • 1 <= s.length <= 10^5
  • 1 <= x, y <= 10^4
  • s consists of lowercase English letters.

Did this problem appear in one of your interviews?

Responses stay private.

Acceptance rate: 0%

© 2026 impol.dev. All rights reserved.PrivacyTerms