15% off all plans & roadmaps Use code
See plansProblem editorial
You are given piles, where piles[i] is the number of stones in the i-th pile from left to right. Two players take turns, and all piles must be taken in their original order: on a turn, a player removes a consecutive prefix of the remaining piles.
Stone Game II is a Dynamic Programming (DP) Patterns problem, in the Interval DP subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
The reference solution runs in O(n^3), where n is piles.size(). There are O(n^2) states, and each state considers O(n) possible moves. time and O(n^2) for the memoization table, plus O(n) for suffix sums and recursion stack. space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Stone Game II is a Dynamic Programming (DP) Patterns problem, in the Interval DP subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.