Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b8c7c0e

Browse files
committed
O(nlogn) time and O(n) space using max heap.
1 parent dc8a236 commit b8c7c0e

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

1046. Last Stone Weight/1046. Last Stone Weight.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,8 @@ def lastStoneWeight(self, stones: List[int]) -> int:
3131
max_heap = [-val for val in stones]
3232
heapq.heapify(max_heap)
3333
while len(max_heap) > 1:
34-
y = (-1) * heapq.heappop(max_heap)
35-
x = (-1) * heapq.heappop(max_heap)
36-
if x == y:
37-
if not max_heap: # consider a case [1,1]
38-
return 0
39-
continue
40-
else:
41-
heapq.heappush(max_heap,x-y)
42-
return max_heap[0] if max_heap[0] > 0 else (-1)*max_heap[0]
34+
stone1 = (-1) * heapq.heappop(max_heap)
35+
stone2 = (-1) * heapq.heappop(max_heap)
36+
if stone1 != stone2:
37+
heapq.heappush(max_heap,-(stone1-stone2))
38+
return -max_heap[0] if max_heap else 0

0 commit comments

Comments
 (0)