Skip to content

Commit 20f5f7d

Browse files
authored
Create number-of-orders-in-the-backlog.py
1 parent e0bda3b commit 20f5f7d

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(nlogn)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def getNumberOfBacklogOrders(self, orders):
6+
"""
7+
:type orders: List[List[int]]
8+
:rtype: int
9+
"""
10+
MOD = 10**9 + 7
11+
buy, sell = [], [] # max_heap, min_heap
12+
for p, a, t in orders:
13+
if t == 0:
14+
heapq.heappush(buy, [-p, a])
15+
else:
16+
heapq.heappush(sell, [p, a])
17+
while sell and buy and sell[0][0] <= -buy[0][0]:
18+
k = min(buy[0][1], sell[0][1])
19+
tmp = heapq.heappop(buy)
20+
tmp[1] -= k
21+
if tmp[1]:
22+
heapq.heappush(buy, tmp)
23+
tmp = heapq.heappop(sell)
24+
tmp[1] -= k
25+
if tmp[1]:
26+
heapq.heappush(sell, tmp)
27+
return reduce(lambda x, y: (x+y) % MOD, (a for _, a in buy + sell))

0 commit comments

Comments
 (0)