Game Of Stones-HackerRank Solution in Java

import java.util.Scanner;

public class GameOfStones
{
    public static String gameOfStones(int n)
    {
        boolean[] dp = new boolean[n+1];
        if(n>=0) dp[0] = false;
        if(n>=1) dp[1] = false;
        
        for(int i=2;i<=n;i++)
        {
            if(i>=2 && !dp[i-2])
            {
                dp[i] = true;
            }
            else if(i>=3 && !dp[i-3])
            {
                dp[i] = true;
            }
            else if(i>=5 && !dp[i-5])
            {
                dp[i] = true;
            }
            else
            {
                dp[i] = false;
            }
        }
        return dp[n] ? "First" : "Second";
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        for (int i=0; i<t; i++)
        {
            int n= sc.nextInt();
            System.out.println(gameOfStones(n));
        }
        sc.close();
    }
}

Sample Input

8
1
2
3
4
5
6
7
10

Sample Output:

Second
First
First
First
First
First
Second
First

Leave a comment