/
1801.number-of-orders-in-the-backlog.cpp
65 lines (58 loc) · 1.83 KB
/
1801.number-of-orders-in-the-backlog.cpp
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=1801 lang=cpp
*
* [1801] Number of Orders in the Backlog
*/
// @lc code=start
class Solution
{
public:
int getNumberOfBacklogOrders(vector<vector<int>> &orders)
{
using PII = pair<int, int>;
priority_queue<PII, vector<PII>, less<>> buy_pq; //{price,amount}
priority_queue<PII, vector<PII>, greater<>> sell_pq;
long res = 0;
const long M = 1e9 + 7;
for (int i = 0; i < orders.size(); ++i)
{
int p = orders[i][0];
int n = orders[i][1];
res = (res + n) % M;
if (orders[i][2] == 0)
{
while (!sell_pq.empty() && sell_pq.top().first <= p && n > 0)
{
auto [price, amount] = sell_pq.top();
sell_pq.pop();
long num = min((long)amount, (long)n);
amount -= num;
n -= num;
res = (res - num * 2 + M) % M;
if (amount > 0)
sell_pq.push({price, amount});
} //while
if (n > 0)
buy_pq.push({p, n});
} //if
else
{
while (!buy_pq.empty() && buy_pq.top().first >= p && n > 0)
{
auto [price, amount] = buy_pq.top();
buy_pq.pop();
long num = min((long)amount, (long)n);
amount -= num;
n -= num;
res = (res - num * 2 + M) % M;
if (amount > 0)
buy_pq.push({price, amount});
} //while
if (n > 0)
sell_pq.push({p, n});
} //else
} //for
return res % M;
}
};
// @lc code=end