class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones = [-s for s in stones] heapq.heapify(stones) while len(stones) > 1: first = abs(heapq.heappop(stones)) #linear time for python second = abs(heapq.heappop(stones)) if first > second: heapq.heappush(stones, second - first) #remember that since it's a minHeap we need negative numbers so it's second - first #edge case to account if stones is empty whether originally or after smashing stones.append(0) return abs(stones[0])
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter