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 weight x is destroyed, and the stone of weight y has new weight y - 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
Last Stone Weight II: From Smashing to Partitioning2741Input stones: [2,7,4,1]Group 1{7} = 7Group 2{2,4,1} = 7Key Insight: Optimal stone smashing = Optimal partitioningFind partition with minimum weight differenceFinal Result0Perfect balance achieved: |7 - 7| = 0
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
Asked in
Amazon 15 Google 8
89.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen