Stone Game VIII
Alice and Bob take turns playing a game, with Alice going first.
There are n stones arranged in a row. On each turn, a player must choose an integer x > 1 and remove the leftmost x stones from the row. The player adds the sum of the removed stones to their score, then places a new stone on the left end whose value equals that sum. The game ends when only one stone remains.
Assuming both play optimally, return the maximum score difference (Alice minus Bob).
Examples
Input: [-1,2,-3,4,-5]
Output: 5
Input: [7,-6,5,10,5,-2,-6]
Output: 13
Hints
Define `dp[i]` as the maximum score difference the current player can achieve from position `i` onward, assuming they must take at least 2 piles.
Precompute prefix sums. At position i, the player can take k piles (k >= 2). They get `prefix[i+k-1] - prefix[i-1]` minus the opponent's optimal advantage from position `i+k`.
This can be optimized to O(n) using suffix maximum DP. Let `best[i] = max(dp[i], best[i+1])` to avoid O(n^2) inner loop.
Related Problems
Stone Game VIII
Alice and Bob take turns playing a game, with Alice going first.