Leetcode::number of orders in the backlog

Problem Description

How to solve

Big O (Time, Space)

Code

class Solution {
public:
    
    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
        priority_queue<pair<int,int>> sellHeap; // min-heap
        priority_queue<pair<int,int>> buyHeap; // max-heap

        for(auto order : orders) {
            cout << order[0] << ", " << order[1] << ", " << order[2] << endl;
            // buy
            if (order[2] == 0) {
                // while loof will run at most N times during the entire iteration.
                while(order[1] > 0 && !sellHeap.empty() && order[0] >= -sellHeap.top().first) {
                    int cnt = sellHeap.top().second;
                    if (order[1] >= cnt) {
                        order[1] -= cnt;
                        sellHeap.pop();
                    } else {
                        pair<int,int> x = sellHeap.top();
                        sellHeap.pop();
                        x.second -= order[1];
                        order[1] = 0;
                        sellHeap.push(x);
                    }
                }
                // leftover
                if (order[1] > 0) {
                    buyHeap.push({order[0], order[1]});
                }
            }
            // sell
            else {
                while(order[1] > 0 && !buyHeap.empty() && buyHeap.top().first >= order[0]) {
                    int cnt = buyHeap.top().second;
                    if (order[1] >= cnt) {
                        order[1] -= cnt;
                        buyHeap.pop();
                    } else {
                        pair<int,int> x = buyHeap.top();
                        buyHeap.pop();
                        x.second -= order[1];
                        order[1] = 0;
                        buyHeap.push(x);
                    }
                }
                // leftover
                if (order[1] > 0) {
                    sellHeap.push({-order[0], order[1]});
                }
            }
        } 
        long long MOD = 1e9 + 7;
        long long ans = 0;
        while(!sellHeap.empty()) {
            ans += sellHeap.top().second;
            ans %= MOD;
            sellHeap.pop();
        }
        while(!buyHeap.empty()) {
            ans += buyHeap.top().second;
            ans %= MOD;
            buyHeap.pop();
        }
        return ans;
    }
};