Example 1
- Input
- stones = [2,7,4,1,8,1]
- Output
- 1
Smash 8 and 7 into 1, then 4 and 2 into 2, then 2 and 1 into 1, then the two 1 stones destroy each other, leaving a single 1.
You are given stone weights and repeatedly smash the two heaviest stones, keeping the difference when they differ and destroying both when they match. Return the last remaining weight, or 0 when no stones survive.
Given an array of integers stones, where each entry is the weight of one stone, smash the stones together until at most one remains.
On each turn, pick the two heaviest stones with weights x and y where . When both weights match, the two stones destroy each other; otherwise the lighter stone is destroyed and the heavier stone continues with weight .
Return the weight of the last remaining stone, or 0 when no stones are left.
1 <= stones.length <= 301 <= stones[i] <= 1000Smash 8 and 7 into 1, then 4 and 2 into 2, then 2 and 1 into 1, then the two 1 stones destroy each other, leaving a single 1.
There is only one stone, so no smash happens and its weight is the answer.
The two heaviest stones both weigh 10, so both disappear. The remaining 3 survives without another smash. Equal weights are separate stones, so duplicates must not be collapsed.
The only two stones have equal weights and both disappear. An empty pile returns 0; there is no surviving zero-weight stone.
The rule fixes which pair to smash: always choose the two heaviest live stones, including any difference created earlier. In Example 1, 8 and 7 become 1, so the next pair is 4 and 2 rather than the next two original entries. We only need a collection that retains duplicate weights and repeatedly exposes its two largest values. Sorting provides a direct simulation; a max heap maintains just the ordering needed to get each maximum.
Reveal Repeated Sorting: intuition, complexity, and code
[1] needs no smash, so the answer is that stone itself.[2, 2] destroy each other and leave an empty pile, so return 0 and never index into the empty heap.1 stones in Example 1, can shrink the pile by two at once without pushing anything back.[1,1000] leave 999, which needs no further smash.(a, b) => a - b for numeric weights.Whenever a simulation repeatedly needs the largest or smallest live element, a heap replaces each linear scan or full sort with a logarithmic pop and push.