for price, amount, orderType in orders: if orderType == 0: ans += amount buy[price] += amount self.heappushMax(buyOrder, price) deleteOrder() else: ans += amount sell[price] += amount self.heappushMin(sellOrder, price) deleteOrder() return ans % MOD
classSolution { public: intgetNumberOfBacklogOrders(vector<vector<int>>& orders){ using pii = pair<int, int>; priority_queue<pii, vector<pii>, greater<pii>> sell; priority_queue<pii> buy; for (auto& e : orders) { int p = e[0], a = e[1], t = e[2]; if (t == 0) { while (a && !sell.empty() && sell.top().first <= p) { auto [x, y] = sell.top(); sell.pop(); if (a >= y) { a -= y; } else { sell.push({x, y - a}); a = 0; } } if (a) { buy.push({p, a}); } } else { while (a && !buy.empty() && buy.top().first >= p) { auto [x, y] = buy.top(); buy.pop(); if (a >= y) { a -= y; } else { buy.push({x, y - a}); a = 0; } } if (a) { sell.push({p, a}); } } } long ans = 0; while (!buy.empty()) { ans += buy.top().second; buy.pop(); } while (!sell.empty()) { ans += sell.top().second; sell.pop(); } constint mod = 1e9 + 7; return ans % mod; } };
funcgetNumberOfBacklogOrders(orders [][]int) (ans int) { sell := hp{} buy := hp{} for _, e := range orders { p, a, t := e[0], e[1], e[2] if t == 0 { for a > 0 && len(sell) > 0 && sell[0].p <= p { q := heap.Pop(&sell).(pair) x, y := q.p, q.a if a >= y { a -= y } else { heap.Push(&sell, pair{x, y - a}) a = 0 } } if a > 0 { heap.Push(&buy, pair{-p, a}) } } else { for a > 0 && len(buy) > 0 && -buy[0].p >= p { q := heap.Pop(&buy).(pair) x, y := q.p, q.a if a >= y { a -= y } else { heap.Push(&buy, pair{x, y - a}) a = 0 } } if a > 0 { heap.Push(&sell, pair{p, a}) } } } const mod int = 1e9 + 7 forlen(buy) > 0 { ans += heap.Pop(&buy).(pair).a } forlen(sell) > 0 { ans += heap.Pop(&sell).(pair).a } return ans % mod }