-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLastStoneWeight.py
More file actions
36 lines (25 loc) · 886 Bytes
/
LastStoneWeight.py
File metadata and controls
36 lines (25 loc) · 886 Bytes
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
30
31
32
33
34
35
36
from queue import PriorityQueue
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
pq = PriorityQueue()
for stone in stones:
pq.put(-stone) # negate to act as a max heap since it is a minHeap
while pq.qsize() >= 2:
stone1 = -pq.get()
stone2 = -pq.get()
if stone1 > stone2:
pq.put(-(stone1 - stone2))
return -pq.get() if not pq.empty() else 0
"""
another approach using sort
"""
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
stones.sort()
while(len(stones)>1):
stone1 = stones.pop()
stone2 = stones.pop()
if stone1 > stone2:
stones.append(stone1-stone2)
stones.sort()
return stones[0] if stones else 0