Number of Orders in the Backlog LeetCode solution in Java

1
class Solution {
2

3
PriorityQueue<Order> buyBackLog;
4
PriorityQueue<Order> sellBackLog;
5

6
static int MOD = 1_000_000_007;
7

8
public int getNumberOfBacklogOrders(int[][] orders) {
9

10
// max heap, heapify on price
11
buyBackLog = new PriorityQueue<Order>((a, b) -> (b.price - a.price));
12
// min heap, heapify on price
13
sellBackLog = new PriorityQueue<Order>((a, b) -> (a.price - b.price));
14

15
// handle all order
16
for (int[] order : orders) {
17
int price = order[0];
18
int quantity = order[1];
19
int orderType = order[2];
20

21
if (orderType == 0) {
22
// buy order
23
handleBuyOrder(new Order(price, quantity));
24

25
} else if (orderType == 1) {
26
// sell order
27
handleSellOrder(new Order(price, quantity));
28
}
29
}
30

31
long counts = 0L;
32

33
// count buy backlog
34
while (!buyBackLog.isEmpty()) {
35
counts += buyBackLog.remove().quantity;
36
counts %= MOD;
37
}
38

39
// count sell backlog
40
while (!sellBackLog.isEmpty()) {
41
counts += sellBackLog.remove().quantity;
42
counts %= MOD;
43
}
44

45
return (int) (counts % MOD);
46
}
47

48
private void handleBuyOrder(Order buyOrder) {
49
// just add buyorder, if there is no sell back log
50
if (sellBackLog.isEmpty()) {
51
buyBackLog.add(buyOrder);
52
return;
53
}
54

55
while (!sellBackLog.isEmpty()
56
&& buyOrder.price >= sellBackLog.peek().price
57
&& buyOrder.quantity > 0) {
58
// selloder with minumum price
59
Order sellOrder = sellBackLog.remove();
60

61
if (buyOrder.quantity >= sellOrder.quantity) {
62
buyOrder.quantity -= sellOrder.quantity;
63
sellOrder.quantity = 0;
64
} else {
65
// decrement sell order, add remaining sellorder
66
sellOrder.quantity -= buyOrder.quantity;
67
sellBackLog.add(sellOrder);
68

69
buyOrder.quantity = 0;
70
}
71
}
72

73
// add reaming buyorder
74
if (buyOrder.quantity > 0) {
75
buyBackLog.add(buyOrder);
76
}
77
}
78

79
private void handleSellOrder(Order sellOrder) {
80
// just add sell order, if there is no buy backlog
81
if (buyBackLog.isEmpty()) {
82
sellBackLog.add(sellOrder);
83
return;
84
}
85

86
while (!buyBackLog.isEmpty()
87
&& buyBackLog.peek().price >= sellOrder.price
88
&& sellOrder.quantity > 0) {
89
// buy order with maximum price
90
Order buyOrder = buyBackLog.remove();
91

92
if (sellOrder.quantity >= buyOrder.quantity) {
93
sellOrder.quantity -= buyOrder.quantity;
94
buyOrder.quantity = 0;
95

96
} else {
97
// decrement buy order quantity, add remaining buyorder
98
buyOrder.quantity -= sellOrder.quantity;
99
buyBackLog.add(buyOrder);
100

101
sellOrder.quantity = 0;
102
}
103
}
104

105
// add remaining sell order
106
if (sellOrder.quantity > 0) {
107
sellBackLog.add(sellOrder);
108
}
109
}
110
}
111

112
class Order {
113
int price;
114
int quantity;
115

116
public Order(int price, int quantity) {
117
this.price = price;
118
this.quantity = quantity;
119
}
120
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0