Kth maximum sum of a contiguous subarray of +ve integers in O(nlogS)

前端 未结 3 1741
故里飘歌
故里飘歌 2021-01-13 14:43

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

3条回答
  •  不要未来只要你来
    2021-01-13 15:25

    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.

    1. Construct a max queue 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.
    2. Insert the following pairs into Q: (0, 0), (0, 1) ... (0, N - 1)
    3. Iterate 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).
    4. Your element is on the top of the queue.

提交回复
热议问题