Problem Description
You are given an array of orders where each order is represented as [price, amount, orderType]. A buy order (orderType = 0) can match with a sell order (orderType = 1) in the backlog if the buy price is at least the sell price. Conversely, a sell order may match with a buy order if the buy order's price is at least the sell order's price. Process all orders in sequence, match orders when possible, and finally count the remaining orders in the backlog modulo 10^9 + 7.
Key Insights
- Use two heaps: a max-heap for buy orders and a min-heap for sell orders.
- For a buy order, match with the lowest-priced sell orders (min-heap) as long as the sell price is <= buy price.
- For a sell order, match with the highest-priced buy orders (max-heap) as long as the buy price is >= sell price.
- Update the order amounts accordingly during matching and push back any remaining amounts.
- Use modulo arithmetic for large sums.
Space and Time Complexity
Time Complexity: O(n log n) due to inserting and polling from heaps for each order. Space Complexity: O(n) for the storage of orders in the heaps.
Solution
The solution maintains two heaps:
- A max-heap for buy orders (using negative prices in languages without a built-in max-heap) to quickly access the order with the highest price.
- A min-heap for sell orders to quickly access the order with the lowest price.
For each new order:
- If it is a buy order, continually match it with the smallest priced sell order (if sell price ≤ buy price). Decrease the amounts accordingly. If any buy order amount remains after no match is possible, add it to the max-heap.
- If it is a sell order, continually match it with the highest priced buy order (if buy price ≥ sell price). Adjust amounts, and if any sell order amount remains after matching, add it to the min-heap.
After processing all orders, sum the amounts in both heaps and return the result modulo (10^9 + 7).