#1046
Last Stone Weight
easy· Heap / Priority Queueruns: 0You are given an array of integers stones where stones[i] is the weight of the ith stone. On each turn, pick the two heaviest stones and smash them. If they are equal in weight, both are destroyed; otherwise the survivor has weight equal to the difference. Return the weight of the last remaining stone, or 0 if none remain.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 362
import heapq
class Solution:
def lastStoneWeight(self, stones: list[int]) -> int:
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
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.