C++ | Map Solution | Question Explained
The description of the question is quite difficult to understand. I\'ll put it in an easier way:\n\n1. when you buy (stock), you buy from the lowest sell orders
The description of the question is quite difficult to understand. I\'ll put it in an easier way:\n\n1. when you buy (stock), you buy from the lowest sell orders up to your limit price, until everything available is exhausted;\n2. when you sell (stock), you sell to the highest buy orders to until your own limit price, until everything higher (or equal) than your limit price is exhausted.\n\n```\nclass Solution {\npublic:\n    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {        \n        map<int, long> buys, sells;\n        for (auto& order : orders) {\n            if (order[2] == 0) { // buy order\n                int amount = order[1];\n                while (amount > 0 && !sells.empty() && sells.begin()->first <= order[0]) {\n                    auto it = sells.begin();\n                    int have = it->second;\n                    it->second -= amount;\n                    amount -= have;\n                    if (it->second <= 0) {\n                        sells.erase(it);\n                    }\n                }\n                \n                if (amount > 0) {\n                    if (buys.find(order[0]) == buys.end()) {\n                        buys[order[0]] = amount;\n                    } else {\n                        buys[order[0]] += amount;\n                    }\n                } \n            } else { // sell order\n                int amount = order[1];\n                while (amount > 0 && !buys.empty() && buys.rbegin()->first >= order[0]) {\n                    auto it = prev(buys.end());\n                    int have = it->second;\n                    it->second -= amount;\n                    amount -= have;\n                    if (it->second <= 0) {\n                        buys.erase(it);\n                    }\n                }\n                \n                if (amount > 0) {\n                    if (sells.find(order[0]) == sells.end()) {\n                        sells[order[0]] = amount;\n                    } else {\n                        sells[order[0]] += amount;\n                    }\n                }\n            }\n        }\n        \n        int res = 0, MOD = 1000000007;\n        for (auto it = buys.begin(); it != buys.end(); it++) {\n            res += it->second;\n            res %= MOD;\n        }\n        \n        for (auto it = sells.begin(); it != sells.end(); it++) {\n            res += it->second;\n            res %= MOD;\n        }\n        \n        return res;\n    }\n};\n```
['Tree', 'C']