Problem statement

https://binarysearch.com/problems/Stock-Order-Execution/

Solution

To be honest, problem formulation is not clear at all. What is asked to do is to go order by order and simulate process. When we have buy act, we need to look at previous elements with less or equal price. Notice that it does not matter how much money we will get, it is asked how many stocks will be executed.

Complexity

It is O(n log n) for time and space.

Code

class Solution:
    def solve(self, orders):
        buy, sell, ans = [], [], 0

        for p, q, act in orders:
            if act == 0:
                while sell and sell[0][0] <= p and q:
                    x = min(sell[0][1], q)
                    ans += x
                    q -= x
                    sell[0][1] -= x
                    if sell[0][1] == 0: heappop(sell)
                if q:
                    heappush(buy, [-p, q])
            else:
                while buy and -buy[0][0] >= p and q:
                    x = min(buy[0][1], q)
                    ans += x
                    q -= x
                    buy[0][1] -= x
                    if buy[0][1] == 0: heappop(buy)
                if q:
                    heappush(sell, [p, q])

        return ans