Skip to content
Problem 1049 · LeetCode 1049(opens in a new tab)

Last Stone Weight II

MediumArrays

The array stones lists weights: stone i weighs stones[i]. A move takes any two stones and smashes them. Equal stones both vanish. Otherwise the lighter one vanishes and the heavier one loses that much weight.

You keep making moves until at most one stone is left. Return the smallest weight that last stone can have, or 0 if no stone is left.

Example 1

Input:  stones = [2, 3, 6, 4]
Output: 1
Why:    piles {3, 4} and {2, 6} weigh 7 and 8
2 more examples and the constraints

Example 2

Input:  stones = [9, 3, 4]
Output: 2
Why:    9 against 3 + 4 = 7 leaves 2

Example 3

Input:  stones = [8]
Output: 8
Why:    there is nothing to smash it with

Constraints

  • There are between 1 and 30 stones
  • Every weight is from 1 to 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Choose a sign per stone, with a memoO(n · S)
  2. Subset sums up to halfO(n · S)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeStates touched for 30 stones of weight 100Verdict
Choose a sign per stone, with a memoO(n · S)
Passes; memo and stack cost more
Subset sums up to halfO(n · S)
Best; one small row

n = number of stones, S = sum of all weights (at most 3,000).

Edge cases to test

  • One stone. Nothing to smash, so the answer is that stone: [8] gives 8.
  • Two equal stones. They destroy each other: [5, 5] gives 0.
  • One very heavy stone. [100, 1, 1] gives 98; the light stones can only chip at it.
  • Odd total. The answer is at least 1, since two piles cannot be equal.

Common mistakes

  • Simulating the game greedily, always smashing the two heaviest. That is a different problem and gives wrong answers here.
  • Looping s upwards in the 1D table, which lets a stone be used more than once.
  • Returning total - best instead of total - 2 * best.

How to talk through it

  1. 1Clarify. Can I choose any pair on each turn? Is 0 returned when no stone is left?
  2. 2Reframe. Every stone ends with a + or − sign, so the answer is the smallest |pile A − pile B|.
  3. 3Name the pattern. Get the subset sum closest to half the total: a 0/1 knapsack.
  4. 4Code the 1D table. Walk s downwards so each stone is used at most once.
  5. 5Test out loud. Try one stone, two equal stones and one heavy stone among light ones.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?