Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import heapq
- class Solution:
- def lastStoneWeight(self, stones: List[int]) -> int:
- # 1) Heapify the stones input
- # Use negative elements to simulate a max heap, because
- # Python's heapq implementation makes a min heap by default.
- heap = [-elem for elem in stones]
- heapq.heapify(heap)
- # 2) While heap length > 1
- while len(heap) > 1:
- # Heap pop twice
- heaviest1 = -heapq.heappop(heap)
- heaviest2 = -heapq.heappop(heap)
- # Smash
- remainder = heaviest1 - heaviest2
- # If remainder > 0
- if remainder > 0:
- # Heap push it
- heapq.heappush(heap, -remainder)
- # 3) Return what's left in heap, if any.
- if len(heap) == 1:
- return -heap[0]
- # If nothing in heap, return 0.
- return 0
Add Comment
Please, Sign In to add comment