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.

Challenge:

O(n) time and O(1) memory

Solution:

Assume i is the last coin, we would like to get i-th coin to win this game. If we think backwards, we have to make sure our opponent takes (i-1)-th coin or (i -2)-th coin. In these two cases, we can easily win by taking 2 (respect to he takes (i - 1) or taking 1 (respect to he takes (i - 1)).

Note: %3 is used for optimizing space complexity.

Code:

public class Solution {
    /**
     * @param n: an integer
     * @return: a boolean which equals to true if the first player will win
     */
    public boolean firstWillWin(int n) {
        if (n <= 0) {
            return false;
        }
        switch (n) {
            case 1: return true;
            case 2: return true;
            case 3: return false;
        }
        boolean[] f = new boolean[3];
        f[0] = true;
        f[1] = true;
        f[2] = false;
        for (int i = 3; i < n; i++) {
            if (!f[(i - 1) % 3] || !f[(i - 2) % 3]) {
                f[i % 3] = true;
            }
        }
        return f[(n - 1) % 3];
    }
}

results matching ""

    No results matching ""