CodingNodes / Heap / Priority Queue / Last Stone Weight System design Space play · ←→ step · R restart

Problem

You have a pile of stones, each with a positive weight. Play rounds until at most one stone remains. In every round take the two heaviest stones, with weights y ≥ x, and smash them together:

  • If x == y, both stones are destroyed.
  • Otherwise the lighter one is destroyed, and the heavier one is left with weight y − x.

Return the weight of the last remaining stone, or 0 if every stone was destroyed.

Constraints

  • 1 ≤ stones.length ≤ 30
  • 1 ≤ stones[i] ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n log n) SpaceO(n)

Time: Building the heap takes n pushes, and every round does up to two pops and one push. There are fewer than n rounds, and each heap operation costs O(log n).

Space: The heap holds at most all n stones.

Each round needs the two heaviest stones, and the leftover goes back into the pile. A max-heap hands out the heaviest stone in O(log n) and takes a new stone in O(log n), which is far cheaper than re-sorting the pile every round. The code uses its own array heap (parent of index i is (i − 1) / 2), so the array and tree you see are the real thing.