1046. Last Stone Weight
Repeatedly smash the two heaviest stones together (the lighter's weight is removed, the heavier is reduced by that amount) until at most one stone remains. Return its weight, or 0.
import heapq
def last_stone_weight(stones):
heap = [-s for s in stones]
heapq.heapify(heap)
while len(heap) > 1:
y = -heapq.heappop(heap)
x = -heapq.heappop(heap)
if y != x:
heapq.heappush(heap, -(y - x))
return -heap[0] if heap else 0
Python's heapq is a min-heap, so negating every value turns 'pop the two largest' into 'pop the two smallest' -- a common trick instead of implementing a separate max-heap.