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. 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
Last Stone Weight II - Optimal Solution INPUT stones array 2 7 4 1 [0] [1] [2] [3] Total Sum = 2+7+4+1 = 14 Target: sum/2 = 7 Split into 2 groups minimize |group1 - group2| Subset Sum DP Find subsets summing to values closest to target dp[i] = can sum to i? ALGORITHM STEPS 1 Initialize DP dp[0] = true, rest false 2 Process Each Stone Update reachable sums 3 Find Best Sum Closest to target (7) 4 Calculate Result sum - 2*bestSum Reachable Sums: Stone 2: {0,2} Stone 7: {0,2,7,9} Stone 4: {0,2,4,6,7,9,11,13} Stone 1: {0,1,2,3,4,5,6,7... Best sum <= 7: 7 (OK) Result = 14 - 2*7 = 0 FINAL RESULT Optimal Partition: Group A {7} Sum = 7 Group B {2,4,1} Sum = 7 = |7 - 7| = 0 Difference = 0 OUTPUT 0 Minimum possible weight of remaining stone: 0 [OK - All stones destroyed] Key Insight: This problem is equivalent to partitioning stones into two groups to minimize their difference. Use Dynamic Programming (Subset Sum variant) to find all achievable sums up to total/2. The answer is: totalSum - 2 * (largest achievable sum <= total/2). Time: O(n*sum), Space: O(sum). TutorialsPoint - Last Stone Weight II | Optimal DP Solution
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