forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1046-last-stone-weight.py
29 lines (25 loc) · 957 Bytes
/
1046-last-stone-weight.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones = [-s for s in stones]
heapq.heapify(stones)
while len(stones) > 1:
first = heapq.heappop(stones)
second = heapq.heappop(stones)
if second > first:
heapq.heappush(stones, first - second)
stones.append(0)
return abs(stones[0])
# There's a private _heapify_max method.
# https://github.com/python/cpython/blob/1170d5a292b46f754cd29c245a040f1602f70301/Lib/heapq.py#L198
class Solution(object):
def lastStoneWeight(self, stones):
heapq._heapify_max(stones)
while len(stones) > 1:
max_stone = heapq._heappop_max(stones)
diff = max_stone - stones[0]
if diff:
heapq._heapreplace_max(stones, diff)
else:
heapq._heappop_max(stones)
stones.append(0)
return stones[0]