Leetcode 3222. Find the Winning Player in Coin Game
In this problem, two players alternately take 1, 2, or 3 coins from a pile of n
coins. The player who takes the last coin wins the game. Assuming both players play optimally, you need to determine if the first player is guaranteed to win. If the first player wins, return true; otherwise, return false.
n
represents the initial number of coins.n
?
n
is a non-negative integer and can be as large as 10^9
.n
being zero or negative?
n
is assumed to be non-negative.To determine if the first player will win, consider the following thoughts:
n
is 0, then the game does not proceed, and neither player wins.n
(from 1 to 3), the first player can just take all the remaining coins and win.4, 8, 12, ...
) coins for the second player, the second player will lose if the first player continues to play optimally. This is because the second player can’t avoid leaving some subsequent non-multiple of 4 for the first player, which allows the first player to eventually leave the second player with another multiple of 4.n % 4 != 0
, the first player can win.n % 4 == 0
, the second player can always force a win.class Solution {
public:
bool canWinCoinGame(int n) {
return n % 4 != 0;
}
};
This solution runs in constant time O(1)
since it only involves a modulus operation and a comparison.
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?