## 1717. 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`.

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.

## Rust Solution

``````struct Solution;

impl Solution {
fn maximum_gain(s: String, x: i32, y: i32) -> i32 {
let (a, b, x, y) = if x >= y {
('a', 'b', x, y)
} else {
('b', 'a', y, x)
};
let mut res = 0;
let mut stack1 = vec![];
for c in s.chars() {
if c == b {
if let Some(&d) = stack1.last() {
if d == a {
res += x;
stack1.pop().unwrap();
continue;
}
}
}
stack1.push(c);
}
let mut stack2 = vec![];
for c in stack1 {
if c == a {
if let Some(&d) = stack2.last() {
if d == b {
res += y;
stack2.pop().unwrap();
continue;
}
}
}
stack2.push(c);
}
res
}
}

#[test]
fn test() {
let s = "cdbcbbaaabab".to_string();
let x = 4;
let y = 5;
let res = 19;
assert_eq!(Solution::maximum_gain(s, x, y), res);
let s = "aabbaaxybbaabb".to_string();
let x = 5;
let y = 4;
let res = 20;
assert_eq!(Solution::maximum_gain(s, x, y), res);
}
``````

Having problems with this solution? Click here to submit an issue on github.