Stone Game II

Alice and Bob play with a row of piles, Alice first, starting with M = 1. On a turn, a player takes all stones from the first X remaining piles, where 1 <= X <= 2M, and then M becomes max(M, X). The game ends when no piles remain. Both play optimally. Return the maximum number of stones Alice can get.

30:00

Stone Game II
medium
Free written solution
Topics
Companies

Alice and Bob play with a row of piles, Alice first, starting with M = 1. On a turn, a player takes all stones from the first X remaining piles, where 1 <= X <= 2M, and then M becomes max(M, X). The game ends when no piles remain. Both play optimally. Return the maximum number of stones Alice can get.

Example 1:
Input: {"piles":[2,7,9,4,4]}
Output: 10
Constraints:
  • 1≤piles.length≤1001 \leq \text{piles.length} \leq 100

  • 1≤piles[i]≤1041 \leq \text{piles}[i] \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"piles":[2,7,9,4,4]}

suffix[i] = stones in piles i..end (total 26). Whatever the player to move does not get from that, the opponent gets.

2

0

26

7

1

24

9

2

17

4

3

8

4

4

4

small number under each pile = suffix sum from there

dp[i][M] for the reachable states (blank = never reached)

M\i

0

1

2

3

4

M=1

M=2

Variables
VariableValue
n5
total26
DepthFunction Call
Stack empty
0/18