You are given an array of positive integers where each value is the weight of a stone. In each move you pick any two stones and smash them together. If the two stones have weights a and b (assume a is at least b), the smash destroys both stones and produces a new stone of weight a - b; if the weights are equal, both stones are fully destroyed and no new stone remains.
You keep smashing until at most one stone is left. Return the smallest weight the last remaining stone can have. If every stone is destroyed, return 0.
The key observation is that assigning a plus or minus sign to each stone models every possible sequence of smashes. Therefore the task reduces to splitting the stones into two groups so that the difference between their total weights is as small as possible.
Example 1
Input: stones = [2,7,4,1,8,1]
Output: 1
Split into groups with sums 11 and 12 (for example {2,4,7-ish groupings}); the best achievable difference is 12 - 11 = 1, so the smallest last stone weighs 1.
Example 2
Input: stones = [31,26,33,21,40]
Output: 5
The total is 151. The subset sum closest to 151/2 = 75.5 that is reachable is 73, giving 151 - 2*73 = 5.
Constraints
1 <= stones.length <= 301 <= stones[i] <= 100The total sum of stones is at most 30 * 100 = 3 * 10^3See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI