build an order-book and match-orders
IntuitionFirst thought: I need a sorted data structure to provide me min and max on pricesApproachCould use binary-search-tree or priority-queue; opted for PQ,
# Intuition
First thought: I need a sorted data structure to provide me min and max on prices
# Approach
Could use binary-search-tree or priority-queue; opted for PQ, because I really do not need to sort each node, just need the min for asks and max for bids.


# Complexity
- Time complexity:
O(nlogn)

- Space complexity:
O(n)

# Code
```java []
class Solution {
    final int BUY = 0, ASK = 1;
    final PriorityQueue<int[]> asks = new PriorityQueue<>((a, b) -> a[0] - b[0]);
    final PriorityQueue<int[]> bids = new PriorityQueue<>((a, b) -> b[0] - a[0]);

    public int getNumberOfBacklogOrders(int[][] orders) {

        for (int[] newOrder : orders) {
            if (newOrder[2] == BUY) bids.offer(newOrder);
            else asks.offer(newOrder);
            matchOrders();
        }
        return (int) (remainingQuantity() % 1000_000_007);
    }

    void matchOrders() {
        while (bids.size() > 0 && asks.size() > 0 && bids.peek()[0] >= asks.peek()[0]) {
            int quantityTraded = Integer.min(bids.peek()[1], asks.peek()[1]);
            bids.peek()[1] -= quantityTraded;
            asks.peek()[1]  -= quantityTraded;
            if (bids.peek()[1] == 0) bids.poll();
            if (asks.peek()[1] == 0) asks.poll();
        }
    }

    long remainingQuantity() {
        long totalQuantity = 0;
        while (bids.size() > 0 || asks.size() > 0) {
            totalQuantity += bids.size() > 0 ? bids.poll()[1] : 0;
            totalQuantity += asks.size() > 0 ? asks.poll()[1] : 0;
        }
        return totalQuantity;
    }
}
```
['Array', 'Sorting', 'Heap (Priority Queue)', 'Java']