I was reading this editorial and got confused with this statement:
If the array elements are all non-negative, we can use binary search to find the an
I think it can be done in O(Klogn)
. sum[i]
is defined as a prefix sum of the given array up to index i
. It can sometimes be faster than the previous solution.
Q
containing pairs of indices (i, j)
. The order is (a, b) < (c, d)
iff sum[b] - sum[a - 1] < sum[d] - sum[d - 1] else if b - a < d - c else if b < d
.Q
: (0, 0), (0, 1) ... (0, N - 1)
K - 1
times and in every iteration pop the top element e = (i, j)
off the Q
and if i < j
then insert (i + 1, j)
.