LeetCode #1049 Medium

Last Stone Weight II

Last Stone Weight II is LeetCode 1049 (Medium). You get an array stones of positive weights. Each turn, pick any two stones with weights x <= y and smash them together:

  • If x == y, both stones are destroyed.
  • Otherwise x is destroyed and y becomes y - x.

Keep going until at most one stone is left. Return the smallest possible weight of that stone, or 0 if no stone is left.

There are at most 30 stones, each weighing at most 100, so the total weight is at most 3,000. That small total is what makes a table over sums affordable.

Constraints
  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 100
dynamic-programmingknapsack
Open on LeetCode ↗
02

Intuition

Each time a stone is smashed, its weight is either added to the survivor or taken away from it. So the last stone always equals (sum of one group of stones) − (sum of the rest), for some way of splitting the stones into two piles.

With total S and one pile summing to s, the last stone is S − 2s. To make it small, make s as close to S / 2 as possible without going over.

That is a subset sum question: which pile sums up to S / 2 can you build from the stones? A table of yes/no values over those sums answers it, and the best reachable sum gives the answer.

How to spot this pattern

"Split items into two groups so the group sums are as close as possible" is subset sum with target half the total. Partition Equal Subset Sum asks whether the gap can be 0, Target Sum counts the ways to place signs, and this problem asks for the smallest gap.

03

Approach

Try it first

Before reading on, smash [31, 26, 33, 21, 40] by always taking the two heaviest stones. Then try to split the same stones into two piles with sums as close as you can. Which gives the smaller last stone?

1

Aim one pile at half the total

Compute S = sum(stones) and half = S // 2. The smaller pile can never be more than half, so only sums from 0 to half matter, and the answer is S - 2 * best for the largest reachable best.

2

Mark which sums can be made

Make a list dp of half + 1 booleans, where dp[t] means some group of stones sums to exactly t. Set dp[0] = True, because a pile with no stones sums to 0.

3

Add stones one by one, sums high to low

For each stone w, go through t from half down to w and set dp[t] = True when dp[t - w] is true. Going downward means dp[t - w] still describes the stones before w, so each stone is used at most once.

4

Take the largest reachable sum

Scan t down from half and stop at the first dp[t] that is true. That pile is as close to half as the stones allow, and S - 2 * t is the smallest last stone.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lastStoneWeightII(self, stones):
▶3 total = sum(stones)
▶4 half = total // 2
▶5 dp = [True] + [False] * half
▶6 for w in stones:
▶7 for t in range(half, w - 1, -1):
▶8 if dp[t - w]:
▶9 dp[t] = True
▶10 for t in range(half, -1, -1):
▶11 if dp[t]:
▶12 return total - 2 * t
stones · total 23274181pile sums you can make, up to 110two piles, smashed against each otheronly pile sums up to 11 matter
total23
half11
However you smash them, the stones end up split into two piles that cancel each other out, and the last stone is the difference between the pile sums. To make that difference small, make one pile as close to half of 23 as you can. Sum 0 is always possible: a pile with no stones.
stones · total 23274181pile sums you can make, up to 1102two piles, smashed against each otheradd 2 → 1 new sum
stone2
new sums2
Putting stone 2 on top of every sum made so far gives 2. The loop runs from high sums down to low, so a sum just made with this stone is never used again for the same stone.
stones · total 23274181pile sums you can make, up to 110279two piles, smashed against each otheradd 7 → 2 new sums
stone7
new sums7, 9
Putting stone 7 on top of every sum made so far gives 7, 9. Every older sum stays possible too: you can always leave this stone out of the pile.
stones · total 23274181pile sums you can make, up to 1102467911two piles, smashed against each otheradd 4 → 3 new sums
stone4
new sums4, 6, 11
Putting stone 4 on top of every sum made so far gives 4, 6, 11. Every older sum stays possible too: you can always leave this stone out of the pile.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each otheradd 1 → 5 new sums
stone1
new sums1, 3, 5, 8, 10
Putting stone 1 on top of every sum made so far gives 1, 3, 5, 8, 10. Every older sum stays possible too: you can always leave this stone out of the pile.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each otheradd 8 → nothing new
stone8
new sumsnone
Stone 8 adds no new sum up to 11: every sum it could reach is already possible, or goes past half.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each otheradd 1 → nothing new
stone1
new sumsnone
Stone 1 adds no new sum up to 11: every sum it could reach is already possible, or goes past half.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each otherhalf the total is reachable: 11
best pile11
other pile12
Scanning down from 11, the first sum you can make is 11 itself, so the piles are as even as the total allows.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each other12−11=1other pilelit stoneslast stonepile of 11 against pile of 12
lit pile4 + 7= 11
other pile12
The lit stones make the sum 11. Every smash takes the same weight off both piles, so the gap between them, 1, never changes and is what remains at the end.
stones · total 23274181pile sums you can make, up to 1101234567891011two piles, smashed against each other12−11=1other pilelit stoneslast stoneanswer: 1
answer123 − 2 × 11
The smallest possible last stone is 1. No split can do better, because no pile closer to half the total can be made.
05

Common pitfalls

Playing the game greedily with a heap

✗ Wrong
smash the two heaviest stones each turn
✓ Right
split the stones into two piles closest to half

Here you choose the pairs, and the greedy choice is not the best one. On [31, 26, 33, 21, 40] it leaves 9, while the piles {40, 33} and {31, 26, 21} (73 and 78) leave 5.

Looping the sums upward

✗ Wrong
for t in range(w, half + 1):
✓ Right
for t in range(half, w - 1, -1):

Going upward, a sum just made with w is read again in the same pass, so one stone counts twice. On [1, 4] the sum 2 looks reachable as 1 + 1, giving 1 instead of the correct 3.

06

Edge cases

A single stone, e.g. [5]

half is 2 and only sum 0 is reachable, so the answer is 5 - 0 = 5: nothing can be smashed.

Stones that cancel exactly, e.g. [3, 3, 2, 4]

Half of 12 is 6, and {3, 3} makes it, so the answer is 0 and no stone is left.

07

Complexity

Time
O(n · S)
Space
O(S)
Each of the n stones sweeps at most S / 2 sums, where S is the total weight. With 30 stones and S at most 3,000 that is about 45,000 updates. The table holds S / 2 + 1 booleans.
08

Last Stone Weight II FAQ

How is it different from Last Stone Weight?

In Last Stone Weight you must always smash the two heaviest stones, so a heap simply plays the game out. Here you pick the pairs, so the question becomes a subset sum DP over pile sums.

Can every split into two piles really be reached by smashing?

For the best split, yes. Smash a stone from the heavier pile against one from the lighter pile and return any leftover to its own pile: both pile sums drop by the same amount, so their gap stays fixed. Repeat until the lighter pile is empty. If the heavier pile still held two or more stones, moving one of them (with the original stones it came from) across at the start would have given a smaller gap, which the best split does not allow. So exactly one stone, of weight equal to the gap, is left.