Problem Description
Given a row of stones where each stone has an associated positive integer value (provided in an array), Alice and Bob play a game. In each round, Alice splits the row into two non-empty parts. Bob then computes the sum of stones for each part and discards the part with the larger sum (if they are equal, Alice chooses which one to discard). Alice’s score increases by the sum of the remaining part. The game continues on the remaining stones until only a single stone is left. The task is to compute the maximum score that Alice can obtain if she plays optimally.
Key Insights
- The game is solved via dynamic programming (DP) because the decision at each step depends on the outcome of future moves.
- Precomputed prefix sums are used to quickly calculate the sum of any subarray.
- Define a state function f(l, r) representing the maximum score Alice can achieve when considering the subarray from index l to r.
- When splitting the array at position i (where l <= i < r), calculate the left subarray’s sum and compare it with the right subarray’s sum.
- Depending on the comparison:
- If left sum < right sum, Bob discards the right segment and the score gained is left sum plus f(l, i).
- If left sum > right sum, Bob discards the left segment and the score gained is right sum plus f(i+1, r).
- If equal, Alice can decide, hence the score is left sum plus the maximum of f(l, i) and f(i+1, r).
- Base case: When the subarray length is one (l == r), no move can be made; hence, the score is zero.
- Although the naive recursive formulation might be O(n³) in the worst-case, optimizations (such as using binary search or DP table cuts using monotonicity properties) can reduce the average-case complexity.
Space and Time Complexity
Time Complexity: O(n³) in the worst-case with the straightforward recursive DP approach; optimizations can reduce this. Space Complexity: O(n²) due to the storage used for the DP memoization table and O(n) for the prefix sum array.
Solution
We can solve this problem using recursion with memoization. First, precompute a prefix sum array so that any subarray sum can be computed in constant time. Define a function f(l, r) which computes the maximum score Alice can obtain for the segment from index l to r of the stoneValue array. For every possible cut position between l and r, we compute the left and right sums. Depending on whether the left sum is less than, greater than, or equal to the right sum, we recursively compute the corresponding state. The key idea is to simulate Alice’s optimal decisions in each state while caching intermediate results to avoid recomputation. This approach efficiently explores all valid moves and aggregate the optimal answer.