Leetcode Problem 1801. Number of Orders in the Backlog

1801. Number of Orders in the Backlog

Leetcode Solutions

Using Priority Queues to Manage Buy and Sell Order Backlogs

  1. Initialize a max heap for buy orders and a min heap for sell orders.
  2. Iterate through each order in the input list.
  3. If the order is a buy order, add it to the buy heap. If it is a sell order, add it to the sell heap.
  4. After adding an order to its respective heap, check if there is a match at the top of both heaps (buy price >= sell price).
  5. If a match is found, execute the orders by reducing the amount from both orders by the minimum of their amounts.
  6. If an order is fully executed (amount becomes 0), remove it from the heap.
  7. If an order is partially executed, push the remaining amount back into the heap.
  8. Repeat steps 4-7 until no more matches can be made.
  9. After processing all orders, sum the amounts of all remaining orders in both heaps.
  10. Return the sum modulo 10^9 + 7.
UML Thumbnail

Brute Force Approach with Sorted Lists

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...