Блог пользователя uttamkumarreddy123

Автор uttamkumarreddy123, история, 22 месяца назад, По-английски

You are given an array A of size N.

Let B denote the list of all N*(N+1)/2 subarray sums of A sorted in non-increasing order.

Your task is to return the Kth element in B. Since the answer can be very large return it modulo 10+7

1<=N<=10**5 1<=K<=min(N*(N+1)/2,10**5) 1<=a[i]<=10**9

  • Проголосовать: нравится
  • -2
  • Проголосовать: не нравится

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

apply binary search for a given mid calculate no of subarrays with sum<=mid which can be done using sliding window. now if no of such subarrays>=k then update ans=mid, high=mid-1 else low=mid

»
22 месяца назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

This can be easily solved using binary search and two pointers. For a value $$$VAL$$$, it doesn't require $$$O(N^2)$$$ to count all the subarrays that have $$$sum \lt = VAL$$$, but rather $$$O(N)$$$ or $$$O(N log N)$$$ . Define $$$sum(l,r) = a[l] + ... +a[r]$$$. It's obvious that if $$$ly$$$ $$$ \lt =$$$ $$$lx$$$ $$$ \lt =$$$ $$$rx$$$ $$$ \lt =$$$ $$$ry$$$) then $$$sum(lx,rx)$$$ $$$ \lt =$$$ $$$sum(ly,ry)$$$. Define $$$next[p]$$$ as the maximum value $$$p \lt = n$$$ such that $$$sum(p,next[p]) \lt = VAL$$$ . The number of subarrays satisfy the conditions will be $$$\sum_{p=1}^{n} next[p] - p + 1$$$. It's obvious that $$$next[p] \lt = next[p + 1]$$$, so the values $$$next[p]$$$ for the whole array can be calculated in $$$O(N)$$$ using two pointers or binary search. The overall complexity is $$$O(N log^2 sum)$$$ or $$$O(N log sum)$$$