Problem Link

Description


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.
    <ul>
    	<li>For example, when removing <code>&quot;ab&quot;</code> from <code>&quot;c<u>ab</u>xbae&quot;</code> it becomes <code>&quot;cxbae&quot;</code>.</li>
    </ul>
    </li>
    <li>Remove substring <code>&quot;ba&quot;</code> and gain <code>y</code> points.
    <ul>
    	<li>For example, when removing <code>&quot;ba&quot;</code> from <code>&quot;cabx<u>ba</u>e&quot;</code> it becomes <code>&quot;cabxe&quot;</code>.</li>
    </ul>
    </li>
    

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
Explanation:
- Remove the "ba" underlined in "cdbcbbaaabab". Now, s = "cdbcbbaaab" and 5 points are added to the score.
- Remove the "ab" underlined in "cdbcbbaaab". Now, s = "cdbcbbaa" and 4 points are added to the score.
- Remove the "ba" underlined in "cdbcbbaa". Now, s = "cdbcba" and 5 points are added to the score.
- Remove the "ba" underlined 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 <= 105
  • 1 <= x, y <= 104
  • s consists of lowercase English letters.

Solution


Python3

class Solution:
    def maximumGain(self, s: str, cx: int, cy: int) -> int:
        N = len(s)
        
        def helper(s, target, cost):
            res = 0
            stack = []
 
            for x in s:
                stack.append(x)
 
                while len(stack) >= 2:
                    if stack[-1] == target[-1] and stack[-2] == target[-2]:
                        stack.pop()
                        stack.pop()
                        res += cost
                    else:
                        break
            
            return "".join(stack), res
 
        if cx >= cy:
            s, cost1 = helper(s, "ab", cx)
            s, cost2 = helper(s, "ba", cy)
            return cost1 + cost2
        else:
            s, cost1 = helper(s, "ba", cy)
            s, cost2 = helper(s, "ab", cx)
 
            return cost1 + cost2