If O (Q)> = O (log N):
Sorting the initial indexes of arrays in the sort order of their elements, for example:
values: [50, 10, 20, 40, 30] -> [10, 20, 30, 40, 50] indices: [#0, #1, #2, #3, #4] -> [#1, #2, #4, #3, #0]
Then, for each query, scan the sorted indices from left to right and add the values โโof the first k elements whose indices are within the range ([l, r]). The complexity will be O (QN + N log N) = O (QN) - again, provided that O (Q)> = O (log N).
There is a way to improve this by first sorting the ranges of queries and then running all the queries in a single scan of sorted indexes, but there is no way to predict how this will affect complexity without knowing anything special about the length of the ranges.
source share