Maximum Score From Removing Substrings

medium array greedy stack

Problem

You are given a string s made of lowercase letters and two integers x and y. You may repeatedly delete a substring "ab" to earn x points, or delete a substring "ba" to earn y points. After each deletion the remaining characters join together, which can create new "ab" or "ba" pairs. Return the maximum total points you can collect.

Inputs = "cdbcbbaaabab", x = 4, y = 5
Output19
Since y > x, remove every "ba" first (worth 5 each), then every "ab" (worth 4 each). Three "ba" removals (+5 each) and one leftover "ab" removal (+4) give 5 + 5 + 5 + 4 = 19.

def maximum_gain(s, x, y):
    a, b = ('a', 'b', x), ('b', 'a', y)
    if x < y:
        a, b = b, a
    score = 0
    score += sweep(s, a)
    s = leftover(s, a)
    score += sweep(s, b)
    return score
function maximumGain(s, x, y) {
  let a = ['a', 'b', x], b = ['b', 'a', y];
  if (x < y) { [a, b] = [b, a]; }
  let score = 0;
  score += sweep(s, a);
  s = leftover(s, a);
  score += sweep(s, b);
  return score;
}
class Solution {
    public int maximumGain(String s, int x, int y) {
        char f1 = 'a', s1 = 'b'; int v1 = x, v2 = y;
        if (x < y) { f1 = 'b'; s1 = 'a'; v1 = y; v2 = x; }
        int score = 0;
        score += sweep(s, f1, s1, v1);
        s = leftover(s, f1, s1);
        score += sweep(s, swap(f1), swap(s1), v2);
        return score;
    }
}
int maximumGain(string s, int x, int y) {
    char f = 'a', g = 'b'; int v1 = x, v2 = y;
    if (x < y) { f = 'b'; g = 'a'; v1 = y; v2 = x; }
    int score = 0;
    score += sweep(s, f, g, v1);
    s = leftover(s, f, g);
    score += sweep(s, g, f, v2);
    return score;
}
Time: O(n) Space: O(n)