A till records n distinct integer sale amounts. Starting from an empty binary search tree, insert the sale amounts in the order given, using the standard BST rule: to insert a key x, walk down from the root, going left if x is smaller than the current node and right if x is larger, until an empty spot is reached, where a new node is created. No rebalancing is performed.
You are given q range queries. Query i gives two integers lo_i and hi_i (lo_i ≤ hi_i); its value is the sum of every sale amount x in the tree with lo_i ≤ x ≤ hi_i (0 if none qualify). Report the grand total: the sum of the values of all q queries added together, as a single integer.
Line 1: an integer n.
Line 2: n space-separated distinct integers — the sale amounts, in insertion order.
Line 3: an integer q.
Next q lines: two space-separated integers lo_i hi_i.
A single integer: the grand total across all q range queries.
Example 1
Input
5 5 3 8 1 4 2 2 5 0 10
Expected
33
Explanation
Sale amounts are {1,3,4,5,8}. Query [2,5] sums 3+4+5=12. Query [0,10] sums all of them: 1+3+4+5+8=21. Grand total = 12+21 = 33.
Example 2
Input
4 10 20 5 15 1 6 16
Expected
25
Explanation
Sale amounts are {5,10,15,20}. Only 10 and 15 fall in [6,16], summing to 25. There is only one query, so the grand total is 25.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →