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. Best partition is around 75-76. We can achieve 76 vs 75, giving minimum final weight of |76-75| = 1. But optimal stone smashing gives us 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
Understanding the Visualization
1
Input
Array of stone weights to be smashed
2
Transform
Convert to partition problem for minimal difference
3
Output
Minimum possible final stone weight
Key Takeaway
🎯 Key Insight: Stone smashing game is equivalent to partitioning into two balanced groups
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code