Skip to content

Commit 0241b50

Browse files
committed
Runtime: 66 ms (Top 82.26%) | Memory: 45.70 MB (Top 32.26%)
1 parent dbad55f commit 0241b50

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

scripts/algorithms/R/Remove Colored Pieces if Both Neighbors are the Same Color/Remove Colored Pieces if Both Neighbors are the Same Color.js

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,30 @@
1+
// Runtime: 66 ms (Top 82.26%) | Memory: 45.70 MB (Top 32.26%)
2+
3+
/**
4+
* @param {string} colors
5+
* @return {boolean}
6+
*/
17
var winnerOfGame = function(colors) {
2-
const n = colors.length;
3-
const stack = [];
4-
5-
let alice = 0;
6-
let bob = 0;
7-
8-
for (let i = 0; i < n; ++i) {
9-
const char = colors[i];
8+
let alice_plays = 0, bob_plays = 0, count = 0;
109

11-
if (stack.length > 1 && stack[stack.length - 1] === char && stack[stack.length - 2] === char) {
12-
stack.pop();
13-
14-
if (char === "A") ++alice;
15-
else ++bob;
10+
for (let i = 1; i < colors.length; i++) {
11+
if (colors[i] == colors[i - 1]) {
12+
count++;
13+
} else {
14+
if (colors[i - 1] == 'A') {
15+
alice_plays += Math.max(0, count - 1);
16+
} else {
17+
bob_plays += Math.max(0, count - 1);
18+
}
19+
count = 0;
20+
}
1621
}
17-
stack.push(char);
22+
23+
if (colors.charAt(colors.length - 1) == 'A') {
24+
alice_plays += Math.max(0, count - 1);
25+
} else {
26+
bob_plays += Math.max(0, count - 1);
27+
}
28+
29+
return alice_plays > bob_plays;
1830
}
19-
20-
return alice > bob ? true : false;
21-
};

0 commit comments

Comments
 (0)