Java PriorityQueue. Simple and Straightforward
Idea is very simple. Maintain a min heap for sell backlogs and maxHeap for buy backlogs.\nWhen order is sell order we will tye to fullfill it from buy backlog w
Idea is very simple. Maintain a min heap for sell backlogs and maxHeap for buy backlogs.\nWhen order is sell order we will tye to fullfill it from buy backlog with making sure conditions are met and vice versa.\n\nAt the end go through both the backlogs and compute total backlogs orders\n\nMore commets and explaination inline\n```\n public int getNumberOfBacklogOrders(int[][] orders) {        \n\t\tQueue<int[]> sellBacklog = new PriorityQueue<int[]>((a, b) -> a[0] - b[0]);\n\t\tQueue<int[]> buyBacklog = new PriorityQueue<int[]>((a, b) -> b[0] - a[0]);\n\n\t\tfor (int[] order : orders) {\n\t\t\tint price = order[0], amt = order[1], type = order[2];\n\t\t\tif (type == 0) { // buy order\n\t\t\t\twhile (!sellBacklog.isEmpty() && sellBacklog.peek()[0] <= price && amt > 0) {\n\t\t\t\t\tif (sellBacklog.peek()[1] > amt) {\n\t\t\t\t\t\t// we have more than required for current buy order so update this sell order and this order is fully completed\n\t\t\t\t\t\tsellBacklog.peek()[1] -= amt;\n\t\t\t\t\t\tamt = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// this whole sell order will be used to fullfil this buy order\n\t\t\t\t\t\tamt -= sellBacklog.remove()[1];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// we still have few more order to fullfil so add it to buy backlog\n\t\t\t\tif (amt > 0) {\n\t\t\t\t\tbuyBacklog.add(new int[] { price, amt });\n\t\t\t\t}\n\t\t\t} else { // sell order\n\t\t\t\twhile (!buyBacklog.isEmpty() && buyBacklog.peek()[0] >= price && amt > 0) {\n\t\t\t\t\tif (buyBacklog.peek()[1] > amt) {\n\t\t\t\t\t\t// we have more than required for current sell order so update this buy order and this sell order is fully completed\n\t\t\t\t\t\tbuyBacklog.peek()[1] -= amt;\n\t\t\t\t\t\tamt = 0;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// this whole buy order will be used to fullfil current sell order\n\t\t\t\t\t\tamt -= buyBacklog.remove()[1];\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// we still have few more order to fullfil so add it to sell backlog\n\t\t\t\tif (amt > 0) {\n\t\t\t\t\tsellBacklog.add(new int[] { price, amt });\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n       // compute total backlog\n\t\tlong result = 0;\n\t\tfor (int[] order : sellBacklog) result += order[1];\t\t\n\t\tfor (int[] order : buyBacklog) result += order[1];\n\t\t\n\t\treturn (int)(result % 1000000007);\n    }\n```
[]