Maximum Score From Removing Substrings LeetCode solution in JavaScript

1
var maximumGain = function (s, x, y) {
2
const n = s.length;
3

4
let totPoints = 0;
5
let stack;
6

7
if (x > y) {
8
stack = remove(s, x, "ab");
9
s = stack.join("");
10
remove(s, y, "ba");
11
} else {
12
stack = remove(s, y, "ba");
13
s = stack.join("");
14
remove(s, x, "ab");
15
}
16

17
return totPoints;
18

19
function remove(str, points, match) {
20
const stack = [];
21

22
for (let i = 0; i < str.length; i++) {
23
const char = str.charAt(i);
24

25
if (stack.length > 0 && stack[stack.length - 1] + char == match) {
26
totPoints += points;
27
stack.pop();
28
} else {
29
stack.push(char);
30
}
31
}
32

33
return stack;
34
}
35
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0