Show problems as
Classic problem #2029MediumArrayMathGreedyMinimaxCountingGame TheoryNim GameZero-Sum Game

Stone Game IX

Real-world version: Crate Removal Duel
Tracked in this browser only
Read Stone Game IX on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A pallet holds a row of crates, and crate i weighs weights[i]. Two loaders, One and Two, empty the pallet in turns, and One always moves first.

On a turn the loader to move must take exactly one crate that is still on the pallet, any one of them, and put it on a shared heap. Straight after a crate lands on the heap, the total weight of every crate now on the heap is read off. If that total is divisible by 3, the loader who has just moved loses and the duel stops there.

If the pallet runs empty and neither loader has lost, Two wins.

Both loaders play as well as the position allows. Return true if One wins the duel, and false otherwise.

Examples

Example 1

Input
weights = [4, 8, 7]
Output
true

One opens by taking the crate of weight 8, so the heap weighs 8, which is not divisible by 3. Two must then take the crate of weight 4 or the crate of weight 7, bringing the heap to 12 or to 15, and both of those are divisible by 3.

Example 2

Input
weights = [6, 9, 12]
Output
false

One has to open with one of the three crates, leaving a heap of 6, 9 or 12, and every one of those totals is divisible by 3, so One loses on the opening move.

Example 3

Input
weights = [5, 11]
Output
false

Whichever crate One opens with, the heap holds 5 or 11 and the duel continues. Two then takes the remaining crate, bringing the heap to 16, which is not divisible by 3, and with the pallet empty and nobody having lost the win goes to Two.

Constraints

  • 1 <= weights.length <= 10^5
  • 1 <= weights[i] <= 10^4

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def first_player_wins(weights: list[int]) -> bool:
Java
public boolean firstPlayerWins(int[] weights)