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 thefirstplay will win or lose?

Have you met this question in a real interview?

Yes

Example

n =1, returntrue.

n =2, returntrue.

n =3, returnfalse.

n =4, returntrue.

n =5, returntrue.

Challenge

O(n) time and O(1) memory

line 13 array initilization need to set two true instead of 1.

line 10 take care 0 case

class Solution {

public:

/\*\*

 \* @param n: an integer

 \* @return: a boolean which equals to true if the first player will win

 \*/

 bool firstWillWin\(int n\) {

    // write your code here 



    if \(n == 0\) {

        return false;

    }

    bool f\[2\] = {true,true};

    for \(int i = 2; i < n; ++i\) {

        f\[i%2\] = !f\[\(i-1\)%2\] \|\| !f\[\(i-2\)%2\]; 

    }

    return f\[\(n-1\)%2\];

}

};

results matching ""

    No results matching ""