Problem Description
Given an array of positive integers representing stone values, two players (Alice and Bob) take turns removing a stone. The cumulative sum of removed stone values is tracked, and the player who makes a move that results in the sum being divisible by 3 loses immediately. If all stones are removed and it is Alice’s turn, Bob wins. Determine if Alice can force a win assuming both players play optimally.
Key Insights
- Only the stone values modulo 3 affect the running sum modulo 3.
- Count stones by their remainder when divided by 3: mod0, mod1, and mod2.
- Stones with a remainder of 0 are “neutral” moves that do not change the sum modulo 3.
- The win/lose outcome depends on the difference between the counts of mod1 and mod2 stones and the parity (odd or even) of mod0 stones.
- Managing the order and selection of mod1 and mod2 moves is critical, and the availability of neutral moves (mod0) can flip turn advantages.
Space and Time Complexity
Time Complexity: O(n) – one pass through the stones array is sufficient.
Space Complexity: O(1) – only a fixed number of counters are used.
Solution
The approach is to first count the stones based on their remainder when divided by 3. If there are no mod1 and mod2 stones, then Alice loses by default. For non-trivial cases, check if the difference between the counts of mod1 and mod2 stones is more than 2, which allows Alice to force a winning situation. If the difference is small, then the parity of mod0 stones becomes decisive; if the count of mod0 stones is odd, Alice has an additional advantage. Ultimately, based on these conditions, the solution returns whether Alice can win.