Coins in a Line
There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.
Could you please decide the first play will win or lose?
Example
n = 1, return true.
n = 2, return true.
n = 3, return false.
n = 4, return true.
n = 5, return true.
Notes:
- Game DP.
- function: f[i] = !f[i-1] || !f[i-2], f[i] is true, means the first player take the ith coin, f[i] is false, means the second player take the ith coin.
- Simplify array to two variants.
public boolean firstWillWin(int n) {
if (n <= 0) {
return false;
}
if (n <= 2) {
return true;
}
boolean p = true;
boolean pp = true;
boolean current = true;
for (int i = 2; i < n; ++i) {
current = !p || !pp;
pp = p;
p = current;
}
return current;
}