Heap/PQ solution with logic [Python]
Logic is:\n Since we need to do a lot of find min/max operations: use 2 heaps:\n\t max-heap b for buy, min-heap s for sell\n\t So, max buy offer is on top of he
Logic is:\n* Since we need to do a lot of **find min/max** operations: use 2 heaps:\n\t* max-heap `b` for buy, min-heap `s` for sell\n\t* So, max buy offer is on top of heap `b`\n\t* Min sell offer is on top of heap `s`\n* Each element of heap is an array: `[price, amount]`\n* *For* each buy/sell order:\n\t* Check for the **good** condition\n\t\t* Good condition is when:\n\t\t\t* Both `b` and `s` are non-empty\n\t\t\t* Top elements satisfy: `s[0][0] <= -b[0][0]` - means `sell price <= buy price`\n\t\t\t* If **good** condition is true: a *sale* will definitely happen\n\t* *While* condition stays **good**, keep performing *sales*\n\t\t* A *sale* means:\n\t\t\t* Pick the top element of both heaps\n\t\t\t* Call their amounts `a1` and `a2`\n\t\t\t* Reduce `a1` and `a2` until one of them becomes `0`\n\t\t\t* If either `a1` or `a2` becomes `0`, pop the heap to which it belongs\n\t\t* Check if the new top of the heap satisfies **good** condition\n* Count the sum of amounts in each heap\n\n```\nclass Solution:\n    def getNumberOfBacklogOrders(self, orders):\n        b, s = [], []\n        heapq.heapify(b)\n        heapq.heapify(s)\n        \n        for p,a,o in orders:\n            if o == 0:\n                heapq.heappush(b, [-p, a])\n                \n            elif o == 1:\n                heapq.heappush(s, [p, a])\n            \n            # Check "good" condition\n            while s and b and s[0][0] <= -b[0][0]:\n                a1, a2 = b[0][1], s[0][1]\n                \n                if a1 > a2:\n                    b[0][1] -= a2\n                    heapq.heappop(s)\n                elif a1 < a2:\n                    s[0][1] -= a1\n                    heapq.heappop(b)\n                else:\n                    heapq.heappop(b)\n                    heapq.heappop(s)\n                    \n        count = sum([a for p,a in b]) + sum([a for p,a in s])\n        return count % (10**9 + 7)\n ```               \n
['Heap (Priority Queue)', 'Python', 'Python3']