You are given a string s and two integers x and y. You can perform two types of operations any number of times.
"ab" and gain x points.
"ab" from "cabxbae" it becomes "cxbae"."ba" and gain y points.
"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 <= 1051 <= x, y <= 104s consists of lowercase English letters.class Solution {
private int score = 0;
private String str = "";
private String solve(char c1, char c2, int pts) {
char[] S = str.toCharArray();
Stack<Character> stk = new Stack<>();
for (char c : S) {
if (c == c1 && !stk.isEmpty() && stk.peek() == c2) {
stk.pop();
score += pts;
} else
stk.push(c);
// System.out.println(stk.toString() + "\t" + score);
}
StringBuilder remainingString = new StringBuilder();
while (!stk.isEmpty()) {
remainingString.append(stk.pop());
}
return remainingString.reverse().toString();
}
public int maximumGain(String s, int x, int y) {
str = s;
if (x < y) {
str = solve('a', 'b', y);
solve('b', 'a', x);
} else {
str = solve('b', 'a', x);
solve('a', 'b', y);
}
return score;
}
}