Description
Repeatedly smash the two heaviest positive-weight stones. Equal stones disappear; otherwise their positive difference returns to the pile. Return the final weight, or zero if none remain.
Solution
import heapq
def last_stone_weight(stones):
heap = [-value for value in stones]
heapq.heapify(heap)
while len(heap) > 1:
first, second = -heapq.heappop(heap), -heapq.heappop(heap)
if first != second:
heapq.heappush(heap, second - first)
return -heap[0] if heap else 0Examples
Example 1
- Input
[[2,7,4,1,8,1]]- Output
1
Repeated smashes leave a stone of weight 1.
Example 2
- Input
[[3,3]]- Output
0
Equal stones destroy each other.
Example 3
- Input
[[5]]- Output
5
No smash is possible.
Approach
Use a max-priority queue to obtain the two largest stones. Push their difference if nonzero and continue until at most one stone remains. Python and Go use negated values in a min-heap.
Time & space
O(n log n) time and O(n) auxiliary space, where n is the initial stone count.