Heap | Simulation
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```python3 []
class Solution:
    def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
        '''
        smallest
        largest

        This can be simulated with heap, because we only care about samllest and largest.
        '''

        M = int(1e9) + 7 
        sellBacklog, buyBacklog = [], []
        
        for price, amount, orderType in orders:
            if orderType:
                # sell
                while buyBacklog and -buyBacklog[0][0] >= price and amount:
                    buyPrice, buyAmount = heapq.heappop(buyBacklog)

                    minimum = min(buyAmount, amount)
                    buyAmount -= minimum
                    amount -= minimum
                    
                    if buyAmount: heapq.heappush(buyBacklog, (buyPrice, buyAmount))
                
                if amount: heapq.heappush(sellBacklog, (price, amount))
            else:
                # buy
                while sellBacklog and sellBacklog[0][0] <= price and amount:
                    sellPrice, sellAmount = heapq.heappop(sellBacklog)

                    minimum = min(sellAmount, amount)
                    sellAmount -= minimum
                    amount -= minimum

                    if sellAmount: heapq.heappush(sellBacklog, (sellPrice, sellAmount))
                
                if amount: heapq.heappush(buyBacklog, (-price, amount))

        return (sum(amount for _, amount in sellBacklog) + sum(amount for _, amount in buyBacklog)) % M

```
['Python3']