SDE & MLE Prep

1046. Last Stone Weight

Problem

Each turn, smash the two heaviest stones x ≤ y together: if they weigh the same both are destroyed, otherwise only a stone of weight y − x remains. Return the weight of the last stone, or 0 if none is left.

Example: [2,7,4,1,8,1] → 1

Simulate with a max-heap: smash the two heaviest, push back the difference.

Complexity: O(n log n).

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        h = [-s for s in stones]
        heapify(h)
        while len(h) > 1:
            a, b = -heappop(h), -heappop(h)
            if a != b:
                heappush(h, -(a - b))
        return -h[0] if h else 0