[LeetCode] Stone Removal Game

3360. Stone Removal Game

Alice and Bob are playing a game where they take turns removing stones from a pile, with Alice going first.

  • Alice starts by removing exactly 10 stones on her first turn.
  • For each subsequent turn, each player removes exactly 1 fewer stone than the previous opponent.

The player who cannot make a move loses the game.

Given a positive integer n, return true if Alice wins the game and false otherwise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
long long sum(long long l, long long r) {
return (r + 1) * r / 2 - l * (l - 1) / 2;
}
bool helper(int n, int l, int r) {
return n >= sum(l,r);
}
public:
bool canAliceWin(int n) {
int l = 1, r = 10, res = 11;
while(l <= r) {
int m = l + (r - l) / 2;
bool ok = helper(n,m,10);
if(ok) {
res = m;
r = m - 1;
} else l = m + 1;
}
return res == 11 ? false : (10 - res) % 2 == 0;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/11/24/PS/LeetCode/stone-removal-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.