LeetCode-in-Java

2029. Stone Game IX

Medium

Alice and Bob continue their games with stones. There is a row of n stones, and each stone has an associated value. You are given an integer array stones, where stones[i] is the value of the ith stone.

Alice and Bob take turns, with Alice starting first. On each turn, the player may remove any stone from stones. The player who removes a stone loses if the sum of the values of all removed stones is divisible by 3. Bob will win automatically if there are no remaining stones (even if it is Alice’s turn).

Assuming both players play optimally, return true if Alice wins and false if Bob wins.

Example 1:

Input: stones = [2,1]

Output: true

Explanation: The game will be played as follows:

The sum of the removed stones is 1 + 2 = 3 and is divisible by 3. Therefore, Bob loses and Alice wins the game.

Example 2:

Input: stones = [2]

Output: false

Explanation: Alice will remove the only stone, and the sum of the values on the removed stones is 2.

Since all the stones are removed and the sum of values is not divisible by 3, Bob wins the game.

Example 3:

Input: stones = [5,1,2,4,3]

Output: false

Explanation: Bob will always win. One possible way for Bob to win is shown below:

Alice loses the game because the sum of the removed stones (15) is divisible by 3. Bob wins the game.

Constraints:

Solution

public class Solution {
    public boolean stoneGameIX(int[] stones) {
        int zero = 0;
        int one = 0;
        int two = 0;
        for (int i : stones) {
            if (i % 3 == 0) {
                zero++;
            } else if (i % 3 == 1) {
                one++;
            } else if (i % 3 == 2) {
                two++;
            }
        }
        if (one == 0 && two == 0) {
            return false;
        }
        int max = Math.max(one, two);
        int min = Math.min(one, two);
        if (zero % 2 == 0) {
            return min != 0;
        }
        if (zero % 2 == 1) {
            return max - 2 > min;
        }
        return false;
    }
}