且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

的+已经为O整数连续的子数组的第k最大总和(nlogS)

更新时间:2022-05-24 22:13:56

假设我们有一个数组,这在指数第i 0的所有元素,以的总和存储第i ,因此,如果所有元素都是非负的,所以

Assume that we have an array sum, which at index ith store the sum of all element from 0 to ith, so, if all element are non-negative, so

 sum[0] <= sum[1] <= sum[2] ... <= sum[i] ... <= sum[n - 1]

我们注意到,一个子阵列的总和(I,J)阵列 A 总和[J] - 总和[我 - 1]

We notice that, the sum of a sub array (i, j) of array A is sum[j] - sum[i - 1]

所以,对于一个数X,我们可以轻松地从子阵列如下的所有总和计算这个数字的排名:

So, Given a number X, we can easily calculate the rank of this number from all sum of sub array of A as follow:

int rank = 0;
for(int i = 0; i < n; i++){
    int index = minimum index which sum[i] - sum[index] >= X;
    //As sum[0] <= sum[1] <=... , we can use binary search to find index
    rank += index;
}

最后,要找到哪个数字是第K 数量,我们可以使用的范围二进制搜索 0至S 并使用上述算法来计算排名,与S是一个子数组的最大总和。

Finally, to find which number is the Kth number, we can use binary search in range O to S and use the above algorithm to calculate the rank, with S is the maximum sum of a subarray.

int start = 0;
int end = S;
while(start <= end){
   int mid = (start + end) >> 1;
   int rank = calRank(mid , sum)
   if(rank < mid)
      end = mid - 1;
   else if(rank > mid)
      start = mid + 1;
   else
      break;
}

所以,时间复杂度为O(nlogS log n)的。

So, time complexity is O(nlogS log n).