Skip to content

Main #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 7, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
O(nlogn) time and O(n) space using max heap.
  • Loading branch information
149ps committed Apr 7, 2022
commit b8c7c0e5cbcd644241ad52902bd4877eaec1c55b
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