🎮 Welcome to Stone Game II! Alice and Bob are back for another strategic stone-collecting battle. This time, the rules have evolved to create an even more engaging game of wits.
The Setup: There are several piles of stones arranged in a row, where piles[i] represents the number of stones in the i-th pile. Alice goes first, and both players want to maximize their own stone collection.
The Rules:
- Players take turns, with Alice starting first
- On each turn, a player can take all stones from the first X remaining piles, where
1 ≤ X ≤ 2M - After taking X piles, we update
M = max(M, X) - Initially,
M = 1 - The game continues until all piles are taken
Your Goal: Assuming both Alice and Bob play optimally (making the best possible moves), determine the maximum number of stones Alice can collect.
Example: If piles = [2,7,9,4,4], Alice can strategically collect 10 stones while Bob gets 6 stones, even though Alice goes first and faces optimal opposition!
Input & Output
Visualization
Time & Space Complexity
We have O(n²) possible states (n positions × n values of M), and for each state we try O(n) moves
Memoization table stores results for O(n²) states, plus O(n) for suffix sums
Constraints
- 1 ≤ piles.length ≤ 100
- 1 ≤ piles[i] ≤ 104
- Both players play optimally
- Alice starts first
- Initially M = 1