Last Stone Weight II - Problem
You are given an array of integers stones where stones[i] is the weight of the i-th stone.
We are playing a game with the stones. On each turn, we choose any two stones and smash them together. Suppose the stones have weights x and y with x ≤ y. The result of this smash is:
- If
x == y, both stones are destroyed - If
x != y, the stone of weightxis destroyed, and the stone of weightyhas new weighty - x
At the end of the game, there is at most one stone left. Return the smallest possible weight of the left stone. If there are no stones left, return 0.
Input & Output
Example 1 — Balanced Partition
$
Input:
stones = [2,7,4,1]
›
Output:
0
💡 Note:
We can partition stones into {7} and {2,4,1}. Both groups have weight 7, so when all stones are smashed optimally, the final weight is |7-7| = 0.
Example 2 — Unbalanced Result
$
Input:
stones = [31,26,33,21,40]
›
Output:
5
💡 Note:
Total weight is 151. We need to partition stones into two groups with minimum difference. Using dynamic programming to find the best subset sum ≤ 75, we can achieve a partition where one group has weight 73 and the other has weight 78, giving minimum final weight of |78-73| = 5.
Example 3 — Single Stone
$
Input:
stones = [1]
›
Output:
1
💡 Note:
Only one stone remains untouched, so the answer is 1.
Constraints
- 1 ≤ stones.length ≤ 30
- 1 ≤ stones[i] ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code