3
PriorityQueue<Order> buyBackLog;4
PriorityQueue<Order> sellBackLog;6
static int MOD = 1_000_000_007;8
public int getNumberOfBacklogOrders(int[][] orders) {10
// max heap, heapify on price11
buyBackLog = new PriorityQueue<Order>((a, b) -> (b.price - a.price));12
// min heap, heapify on price13
sellBackLog = new PriorityQueue<Order>((a, b) -> (a.price - b.price));16
for (int[] order : orders) {18
int quantity = order[1];19
int orderType = order[2];23
handleBuyOrder(new Order(price, quantity));25
} else if (orderType == 1) {27
handleSellOrder(new Order(price, quantity));34
while (!buyBackLog.isEmpty()) {35
counts += buyBackLog.remove().quantity;40
while (!sellBackLog.isEmpty()) {41
counts += sellBackLog.remove().quantity;45
return (int) (counts % MOD);48
private void handleBuyOrder(Order buyOrder) {49
// just add buyorder, if there is no sell back log50
if (sellBackLog.isEmpty()) {51
buyBackLog.add(buyOrder);55
while (!sellBackLog.isEmpty()56
&& buyOrder.price >= sellBackLog.peek().price57
&& buyOrder.quantity > 0) {58
// selloder with minumum price59
Order sellOrder = sellBackLog.remove();61
if (buyOrder.quantity >= sellOrder.quantity) {62
buyOrder.quantity -= sellOrder.quantity;63
sellOrder.quantity = 0;65
// decrement sell order, add remaining sellorder66
sellOrder.quantity -= buyOrder.quantity;67
sellBackLog.add(sellOrder);69
buyOrder.quantity = 0;73
// add reaming buyorder74
if (buyOrder.quantity > 0) {75
buyBackLog.add(buyOrder);79
private void handleSellOrder(Order sellOrder) {80
// just add sell order, if there is no buy backlog81
if (buyBackLog.isEmpty()) {82
sellBackLog.add(sellOrder);86
while (!buyBackLog.isEmpty()87
&& buyBackLog.peek().price >= sellOrder.price88
&& sellOrder.quantity > 0) {89
// buy order with maximum price90
Order buyOrder = buyBackLog.remove();92
if (sellOrder.quantity >= buyOrder.quantity) {93
sellOrder.quantity -= buyOrder.quantity;94
buyOrder.quantity = 0;97
// decrement buy order quantity, add remaining buyorder98
buyOrder.quantity -= sellOrder.quantity;99
buyBackLog.add(buyOrder);101
sellOrder.quantity = 0;105
// add remaining sell order106
if (sellOrder.quantity > 0) {107
sellBackLog.add(sellOrder);116
public Order(int price, int quantity) {118
this.quantity = quantity;