See below code:
vector<long long> temp;
for (int i = l; i <= r; ++i)
{
temp.push_back(holes[i]);
}
sort(temp.rbegin(), temp.rend());
long long needed_H2 = 0;
for (int i = K; i < temp.size(); ++i)
{
needed_H2 += temp[i];
}
Basically, it copies some range [l, r] of original array, sorts it in non-ascending order and then finds sum of this range omitting first K greatest element.
$N$ is size of array on which we will make range queries.
I need to achieve the same in like $O(log^2 N)$ time complexity (if possible), and I wonder about Merge Sort Tree (MST) specifically. If the values would be unique - then I see solution in $O(log^2 N * log M)$ where $M$ is maximum value we will ever potentially check in binary search. The $log^2 N$ factor is due to traversing Merge Sort Tree, and at every node which is in range we look for, we will also do binary search (lower bound) to find first value greater than $X$ given by binary search. So, we perform binary search on the MST asking "how many elements are greater than X" and if we find X such that returned count is equal to K (it must happen if elements are unique and we have more elements than K). To find sum of these K-th largest elements, on MST we can also store prefix sums of sorted ranges which every MST node already stores.
But what if the element are not unique? Can we also solve it?
Lets say count of elements greater than given val is C.
I tried finding minimum value such that the $C >= K$, and then do some adjustmens using minimum value (because I think that if we would exclude all minimum elements from range, so we would search for a minimally greater val such that the C will change,then we would find $C < K$, because the C we found before was the minimal greater than K). At the end, we would substract from sum found on range the (minimum value * ($C - K$))
I wrote code, but unfortunately, it doesnt work as expected. I spent much time debugging, so I think there's something wrong this above idea.
So, can we find sum of first K largest elements in range [l, r] using Merge Sort Tree?