Please, try EDU on Codeforces! New educational section with videos, subtitles, texts, and problems. ×

Maximum length subarray having sum greater than K(Please Help!)

Revision en2, by prabhat7298, 2019-08-20 00:58:09

I want to find largest length subarray having sum greater than k.

One of the solution I found somewhere is binary searching on the length of subarray. Length of subarray can vary from 1 to n. We can binary search in range low=1 to high=n and for every mid=(low+high)/2 we can check for all subarray of length=mid if any subarray has sum greater than k in O(n). If any such subarray exist then we can search for higher length subarray i.e. low=mid+1 otherwise we decrease the search length i.e. high=mid-1.

int maxlen(vector<int> v)
{
    int hi = n, lo = 1, ans = -1, mid, cnt = 0;
    while(lo <= hi) {
        mid = hi+lo>>1;
        if(cnt = count(mid)) {
            ans = mid;
            lo = mid + 1;
        } else {
            hi = mid - 1;
        }
    return ans;
 }

int count(int len) {
    int cnt = 0;
    for(int i = len; i <= n; i++)
        if(prefixsum[i] - prefixsum[i - len] > K)
            cnt++;
    return cnt;
}

What puzzles me is that if we get sum < k for present length subarray then increasing the search length of subarray will ensure that we'll get some subarray having subarray>k. And if we have subarray>k for any length then by decreasing search length we can get more such subarrays having greater than k sum. It could be that we could have decreased search length to get some subarray>k.

So, the question boils down to deciding the predicate of binary search i.e. at each step how we'll decide to change the search range?

PS: I know it can be easily solved by binary searching on prefix subarray rather than on length but I want to know the correctnes of the solution or how it works

Tags #subarray, maximum length

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English prabhat7298 2019-08-20 00:58:09 4
en1 English prabhat7298 2019-08-20 00:56:38 1733 Initial revision (published)