[LeetCode] Number of Orders in the Backlog

1801. Number of Orders in the Backlog

You are given a 2D integer array orders, where each orders[i] = [pricei, amounti, orderTypei] denotes that amounti orders have been placed of type orderTypei at the price pricei. The orderTypei is:

  • 0 if it is a batch of buy orders, or
  • 1 if it is a batch of sell orders.

Note that orders[i] represents a batch of amounti independent orders with the same price and order type. All orders represented by orders[i] will be placed before all orders represented by orders[i+1] for all valid i.

There is a backlog that consists of orders that have not been executed. The backlog is initially empty. When an order is placed, the following happens:

  • If the order is a buy order, you look at the sell order with the smallest price in the backlog. If that sell order’s price is smaller than or equal to the current buy order’s price, they will match and be executed, and that sell order will be removed from the backlog. Else, the buy order is added to the backlog.
  • Vice versa, if the order is a sell order, you look at the buy order with the largest price in the backlog. If that buy order’s price is larger than or equal to the current sell order’s price, they will match and be executed, and that buy order will be removed from the backlog. Else, the sell order is added to the backlog.

Return the total amount of orders in the backlog after placing all the orders from the input. Since this number can be large, return it modulo 109 + 7.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
int getNumberOfBacklogOrders(vector<vector<int>>& orders) {
priority_queue<pair<int,int>,vector<pair<int,int>>, greater<pair<int,int>>> sell;
priority_queue<pair<int,int>> buy;
for(auto& o : orders) {
int p = o[0], a = o[1], t = o[2];
if(t == 0) {
while(!sell.empty() and sell.top().first <= p and a) {
auto [sp, sa] = sell.top(); sell.pop();
auto b = min(a, sa);
a -= b;
sa -= b;
if(sa) sell.push({sp, sa});
}
if(a) buy.push({p,a});
} else if(t == 1) {
while(!buy.empty() and buy.top().first >= p and a) {
auto [bp, ba] = buy.top(); buy.pop();
auto b = min(a, ba);
a -= b;
ba -= b;
if(ba) buy.push({bp, ba});
}
if(a) sell.push({p,a});
}
}
long res = 0, mod = 1e9 + 7;
while(!buy.empty()) {
auto [_, a] = buy.top(); buy.pop();
res = (res + a) % mod;
}
while(!sell.empty()) {
auto [_, a] = sell.top(); sell.pop();
res = (res + a) % mod;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/17/PS/LeetCode/number-of-orders-in-the-backlog/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.