You have a collection of stones with weights. Each turn, smash the two heaviest stones together:
stones = [2, 7, 4, 1, 8, 1]
# Smash 8 and 7 → 8-7=1 remains → [2, 4, 1, 1, 1]
# Smash 4 and 2 → 4-2=2 remains → [1, 1, 1, 2]
# Smash 2 and 1 → 2-1=1 remains → [1, 1, 1]
# Smash 1 and 1 → destroyed → [1]
# Answer: 1
This screams max-heap! We need to repeatedly get the two largest elements. Since Python only has min-heap, negate the values:
# Max-heap trick: push -weight, pop gives -largest
heapq.heappush(heap, -8) # internally [-8, ...]
val = -heapq.heappop(heap) # val = 8
Negate all values and heapify. While len(heap) > 1: pop two largest (negate back). If different, push -(abs(a) - abs(b)). Return -heap[0] if heap else 0.