Magicsheet logo

Stone Game II

Medium
12.5%
Updated 8/1/2025

Stone Game II

What is this problem about?

Stone Game II is a more complex version of the classic stone game. Alice and Bob take turns taking XX piles from the beginning of the row, where 1X2M1 \le X \le 2M. Initially, M=1M = 1. After a player takes XX piles, MM is updated to max(M,X)\max(M, X). The goal is to find the maximum number of stones Alice can collect, assuming both players play optimally.

Why is this asked in interviews?

This problem is a "Medium-to-Hard" challenge that tests your ability to handle multiple changing variables in a state (MM and the current index). It assesses your skill in Dynamic Programming, Prefix Sums, and Memoization. Companies like Uber and Google use it to see if you can handle complex game rules and optimize them using top-down DP.

Algorithmic pattern used

The pattern is Dynamic Programming with Memoization and Prefix Sums.

  • State: dp(i, M) is the maximum stones the current player can get starting from index ii with the current value of MM.
  • Transition: The current player tries taking XX piles (where 1X2M1 \le X \le 2M). The total stones they get is TotalRemainingStones(i) - dp(i + X, max(M, X)).
  • Optimization: Use a prefix sum (specifically, a suffix sum) to quickly calculate the total stones remaining from index ii to the end.

Example explanation (use your own example)

Piles: [2, 7, 9, 4, 4], M=1M = 1.

  • Alice's first move: can take X=1X=1 or X=2X=2 piles.
  • If she takes X=2X=2 ([2, 7]), MM becomes 2. Now Bob can take up to 2×2=42 \times 2 = 4 piles.
  • Alice wants to choose XX such that the stones she gets now plus what she gets in her future turns is maximized. Since Bob also plays optimally, he will try to minimize what Alice gets. The DP handles this by assuming the next state's result is the maximum Bob can get, leaving the rest for Alice.

Common mistakes candidates make

  • Not using Suffix Sums: Re-calculating the sum of remaining piles in every recursive call (O(N)O(N) instead of O(1)O(1)).
  • Incorrect MM update: Forgetting that MM is the maximum of its current value and XX.
  • State definition errors: Not realizing that MM can grow up to NN, making it a necessary part of the DP state.
  • Greedy logic: Trying to take the most stones immediately without considering how it increases MM for the opponent.

Interview preparation tip

When a game's rules involve a variable that changes based on previous moves, that variable must be part of your DP state. For Stone Game II coding problem, the state is (index,M)(index, M).

Similar Questions