Each turn, smash the two heaviest stones x ≤ y together: equal stones are both destroyed, otherwise a stone of weight y − x remains. Return the weight of the last stone, or 0 if none remain.
A max-heap hands out the two heaviest stones in O(log n) each round and takes back the leftover just as fast.
1function lastStoneWeight(stones: number[]): number {2const heap = new MaxPriorityQueue<number>();3for (const s of stones) heap.enqueue(s);4while (heap.size() > 1) {5const y = heap.dequeue(), x = heap.dequeue();6if (y !== x) heap.enqueue(y - x);7}8return heap.size() ? heap.front() : 0;9}
Heapify all stones.
Space: play/pause · ←/→: step