# LeetCode: Number Of Orders In The Backlog Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}// 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 === 012    if (buying) {13      while (!sellPq.isEmpty() && amount > 0) {14        let { element: front } = sellPq.dequeue()15        if (front.price > price) {16          sellPq.enqueue(front)17          break18        }19        const min = Math.min(front.amount, amount)20        amount -= min21        front.amount -= min22        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          break35        }36        const min = Math.min(front.amount, amount)37        amount -= min38        front.amount -= min39        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      053    ) %54    (1e9 + 7)55  )56}```

leetcode

heap

greedy

## Next Post

LeetCode: Maximum Ascending Subarray Sum

Mar 21, 2021

Search Posts