Skip to content

Commit

Permalink
O(nlogn) time and O(n) space using max heap.
Browse files Browse the repository at this point in the history
  • Loading branch information
149ps committed Apr 7, 2022
1 parent dc8a236 commit b8c7c0e
Showing 1 changed file with 5 additions and 9 deletions.
14 changes: 5 additions & 9 deletions 1046. Last Stone Weight/1046. Last Stone Weight.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,8 @@ def lastStoneWeight(self, stones: List[int]) -> int:
max_heap = [-val for val in stones]
heapq.heapify(max_heap)
while len(max_heap) > 1:
y = (-1) * heapq.heappop(max_heap)
x = (-1) * heapq.heappop(max_heap)
if x == y:
if not max_heap: # consider a case [1,1]
return 0
continue
else:
heapq.heappush(max_heap,x-y)
return max_heap[0] if max_heap[0] > 0 else (-1)*max_heap[0]
stone1 = (-1) * heapq.heappop(max_heap)
stone2 = (-1) * heapq.heappop(max_heap)
if stone1 != stone2:
heapq.heappush(max_heap,-(stone1-stone2))
return -max_heap[0] if max_heap else 0

0 comments on commit b8c7c0e

Please sign in to comment.