Last Stone Weight — Heap / Priority Queue
Repeatedly smash the heaviest pair of stones together, keeping the difference if they differ, and report the final weight or nothing.
Heap / Priority Queue · Easy
The problem
In a rock-smashing game you always pick the two biggest rocks and crash them together. You have a pile of stones with positive weights. Each round, take the two heaviest stones and smash them together: if they weigh the same both vanish, otherwise the lighter one vanishes and the heavier one keeps only the difference in weight. Rounds continue until at most one stone is left.
The story
In a rock-smashing game you start with 1 to 12 stones, each weighing 1 to 30. Every round you crash the two heaviest together: if they weigh the same, both shatter; otherwise the lighter one shatters and the heavier one keeps only the difference and goes back with the rest. Play until at most one stone is left, then report its weight, or 0 if none remain.
What to return
- Return the weight of the last remaining stone.
- Return 0 if no stone remains.
- A stone that survives a smash goes back into the pile with its reduced weight.
Constraints
- 1 <= stones.length <= 12
- 1 <= stones[i] <= 30
Example
- Input
stones = [9, 3, 6, 8, 2]- Output
0