c++
class Solution {
public:
struct sCMP {
bool operator()(vector<int> a, vector<int> b) {
return a[0] > b[0];
}
};
struct bCMP {
bool operator()(vector<int> a, vector<int> b) {
return a[0] < b[0];
}
};
int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
priority_queue<vector<int>, vector<vector<int>>, sCMP> sell;
priority_queue<vector<int>, vector<vector<int>>, bCMP> buy;
for (auto x : orders) {
if (x[2] == 0) {
while (x[1] && sell.size() && sell.top()[0] <= x[0]) {
auto tmp = sell.top();
int cnt = min(tmp[1], x[1]);
tmp[1] -= cnt, x[1] -= cnt;
sell.pop();
if (tmp[1]) sell.push(tmp);
}
if (x[1]) buy.push(x);
} else {
while (x[1] && buy.size() && buy.top()[0] >= x[0]) {
auto tmp = buy.top();
int cnt = min(tmp[1], x[1]);
tmp[1] -= cnt, x[1] -= cnt;
buy.pop();
if (tmp[1]) buy.push(tmp);
}
if (x[1]) sell.push(x);
}
}
int sum = 0, mod = 1000000007;
while (sell.size()) {
auto tmp = sell.top();
sell.pop();
sum = (tmp[1] + sum) % mod;
}
while (buy.size()) {
auto tmp = buy.top();
buy.pop();
sum = (tmp[1] + sum) % mod;
}
return sum;
}
};
js
var getNumberOfBacklogOrders = function(orders) {
var sell = new MinPriorityQueue({ priority: (bid) => bid.price });
var buy = new MaxPriorityQueue({ priority: (bid) => bid.price });
for (var [price, amount, orderType] of orders) {
if (!orderType) {
while (amount && sell.size() && sell.front().priority <= price) {
var tmp = sell.dequeue().element;
var cnt = Math.min(amount, tmp.amount);
tmp.amount -= cnt, amount -= cnt;
if (tmp.amount) sell.enqueue({price: tmp.price, amount: tmp.amount});
}
if (amount) buy.enqueue({price, amount});
} else {
while (amount && buy.size() && buy.front().priority >= price) {
var tmp = buy.dequeue().element;
var cnt = Math.min(amount, tmp.amount);
tmp.amount -= cnt, amount -= cnt;
if (tmp.amount) buy.enqueue({price: tmp.price, amount: tmp.amount});
}
if (amount) sell.enqueue({price, amount});
}
}
var sum = 0, mod = 1000000007;
while (buy.size()) sum = (sum + buy.dequeue().element.amount) % mod;
while (sell.size()) sum = (sum + sell.dequeue().element.amount) % mod;
return sum;
};