Mark this tutorial in a binary indexed tree. This is a structure that uses O (n) memory and can perform such tasks:
1. Change the value of a [i] to (to) x, name it add(i,x) ;
2. We return the sum of all [i], I <= m, call it get(x) .
in O (log n) .
Now how to use this for your task. You can do this in 2 steps. First step. Copy, sort, and delete duplicates from the original array. Now you can reassign numbers, so they are in the range [1 ... n].
Step 2. Now go through the array from left to right. Let A [i] be the value in the original array, new [i] the displayed value. (if A = [2, 7, 11, -3, 7], then new = [2, 3, 4, 1, 2]).
Answer: get (new [i] -1).
Update values: add(new[i], 1) for counting, add(new[i], A[i]) for the sum.
Generally. Sort and reassign O (n logn) . Working with an array n * O (log n) = O (n log n) . So the total complexity is O (n logn)
Alternatively use treap .
EDIT: Creating a new array.
Suppose the original array A = [2, 7, 11, -3, 7]
Copy it to B and sort, B = [-3, 2, 7, 7, 11]
Make a unique B = [-3, 2, 7, 11].
Now, to get a new one, you can
- add all items to be displayed in ascending order, for example. (-3 β 1, 2-> 2, 7-> 3, 11-> 4)
- for each element in A, do a binary search on B