You have a collection of stones, each with a positive integer weight. Each turn, choose the two heaviest stones and smash them together. Suppose the heaviest is a and the second heaviest is b. If a == b both are destroyed; if a != b, stone of weight a is destroyed and stone of weight b becomes a - b. Return the weight of the last remaining stone, or 0 if none remain.
stones = [2,7,4,1,8,1]1stones = [1]1stones = [3,3]0PriorityQueue(reverseOrder)a = largest, then b = 2nd largest from the heapa ≠ b: push (a − b) back; if a == b: both destroyed, nothing pushed0We always need the two largest elements, and the heap gives us each in O(log n). With at most n rounds (each removes at least one stone), the total cost is O(n log n). A sorted array would need O(n) per round for insertion — the heap is the natural fit.