Last Stone Weight II
1 approach, code in every language
Problem description
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^3
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Trimming The Bar Rack Down is our own problem on the technique behind Last Stone Weight II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free