Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N
on the chalkboard. On each player’s turn, that player makes a move consisting of:
x
with 0 < x < N
and N % x == 0
.N
on the chalkboard with N - x
.Also, if a player cannot make a move, they lose the game.
Return true
if and only if Alice wins the game, assuming both players play optimally.
N
?
1 <= N <= 1000
.To determine whether Alice wins given she starts first, we can consider the parity of N
:
x=1
, which would make N
an odd number for Bob’s turn.1
, and following this strategy, Bob would eventually have to deal with an even number, switching back to Alice in a better position.N
.This pattern suggests that Alice wins if and only if N
is even.
Here is the implementation following the described strategy:
class Solution {
public:
bool divisorGame(int N) {
return N % 2 == 0;
}
};
The time complexity of this solution is:
This solution effectively utilizes the observation about even and odd numbers in this specific game context, ensuring optimal performance.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?