LeetCode: Number Of Orders In The Backlog Solution

1// const {
2// MinPriorityQueue,
3// MaxPriorityQueue,
4// } = require("@datastructures-js/priority-queue");
5
6var getNumberOfBacklogOrders = function (orders) {
7 const buyPq = new MaxPriorityQueue({ priority: order => order.price })
8 const sellPq = new MinPriorityQueue({ priority: order => order.price })
9
10 for (let [price, amount, orderType] of orders) {
11 const buying = orderType === 0
12 if (buying) {
13 while (!sellPq.isEmpty() && amount > 0) {
14 let { element: front } = sellPq.dequeue()
15 if (front.price > price) {
16 sellPq.enqueue(front)
17 break
18 }
19 const min = Math.min(front.amount, amount)
20 amount -= min
21 front.amount -= min
22 if (front.amount > 0) {
23 sellPq.enqueue(front)
24 }
25 }
26 if (amount > 0) {
27 buyPq.enqueue({ price, amount })
28 }
29 } else {
30 while (!buyPq.isEmpty() && amount > 0) {
31 let { element: front } = buyPq.dequeue()
32 if (front.price < price) {
33 buyPq.enqueue(front)
34 break
35 }
36 const min = Math.min(front.amount, amount)
37 amount -= min
38 front.amount -= min
39 if (front.amount > 0) {
40 buyPq.enqueue(front)
41 }
42 }
43 if (amount > 0) {
44 sellPq.enqueue({ price, amount })
45 }
46 }
47 }
48
49 return (
50 [...buyPq.toArray(), ...sellPq.toArray()].reduce(
51 (acc, { element: el }) => acc + el.amount,
52 0
53 ) %
54 (1e9 + 7)
55 )
56}

Comments

Loading comments...

Tags

leetcode

heap

greedy

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Maximum Ascending Subarray Sum

HoningJS

Search Posts