15% off all plans & roadmaps Use code
See plansProblem editorial
You are given a collection of stones in stones, where each integer represents one stone's weight. In one operation, choose any two remaining stones and smash them together. If their weights are equal, both disappear; otherwise, the lighter stone disappears and the heavier stone is replaced by a stone whose weight is the difference between the two.
Last Stone Weight II is a Dynamic Programming (DP) Patterns problem, in the 1D Array (0/1 Knapsack Subset Sum Style) subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
The reference solution runs in O(n * S), where n is the number of stones and S is the total stone weight. time and O(S) space.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Last Stone Weight II is a Dynamic Programming (DP) Patterns problem, in the 1D Array (0/1 Knapsack Subset Sum Style) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.