Skip to content

Last Stone Weight

EasyHeap / Priority Queue
Decode it first. Clues, constraints, pattern and plan before any code.

You have a pile of stones with weights stones. Each turn, take the two heaviest stones, x <= y, and smash them together:

  • if x == y, both are destroyed;
  • otherwise the x stone is destroyed and the y stone now weighs y - x.

Keep going until at most one stone is left. Return its weight, or 0 if none remain.

[2, 7, 4, 1, 8, 1]  →  1   (8,7 → 1; 4,2 → 2; 2,1 → 1; 1,1 → 0; one stone of 1 left)
[2, 2]              →  0
[1]                 →  1

Constraints

  • 1 <= stones.length <= 30
  • 1 <= stones[i] <= 1000