Ruby - Keep sorted queues for buy and sell orders.
Keep buy queue sorted by price descending.\nKeep sell queue sorted by price ascending.\nBuy by the best price (minimum price - first in the sell queue) while ca
Keep buy queue sorted by price descending.\nKeep sell queue sorted by price ascending.\nBuy by the best price (minimum price - first in the sell queue) while can.\nSell by the best price (maximum price - first in the buy queue) while can.\n\n```ruby\ndef get_number_of_backlog_orders(orders)\n  bq = []; sq = [] # buy queue and sell queue\n  for price, amount, order_type in orders\n    if order_type == 0 # buy\n      amount -= sq.shift[1] while amount > 0 && sq.any? && sq[0][0] <= price && sq[0][1] <= amount\n      if sq.any? && sq[0][0] <= price\n        sq[0][1] -= amount\n      else\n        bq.insert(bq.bsearch_index { |p,| p <= price } || bq.size, [price, amount]) if amount > 0\n      end\n    else # sell\n      amount -= bq.shift[1] while amount > 0 && bq.any? && bq[0][0] >= price && bq[0][1] <= amount\n      if bq.any? && bq[0][0] >= price\n        bq[0][1] -= amount\n      else\n        sq.insert(sq.bsearch_index { |p,| p >= price } || sq.size, [price, amount]) if amount > 0\n      end\n    end\n  end\n  (bq.sum(&:last) + sq.sum(&:last)) % 1000000007\nend\n```
['Binary Tree', 'Ruby']