Problem Statement : Let’s say we have an array A .We have to find longest subarray in which elements greater than x are more than elements not greater than x
I’ve solved the exact same problem 6 months ago. Just convert guys greater than ‘x’ to 1 and others to -1, now find the longest subarray with sum>=0 or sum>=-1 depending on your requirements…
And if you are cheating, then well done!
Code is cheap, and ideas are the only thing that matters.
First, let’s preprocess the prefix and sum of the array and make it as a S array. it cost O(n) time complexity.
Then we sort S arrays from small to large, obviously the range of S arrays is n, we can use bucket sort, it will take O (n) time complexity.
Let’s start with the smallest value of the S array. Let’s set it to S_i, and record the minimum subscript that appears with a variable p, initial p = n + 1.
So for each current S_i, ans = max(ans, i - p), after each layer of S_i is traversed, p is updated once that p = min(p, i). it will take O (n) time complexity.
If the problem was :- Find the longest subarray with sum=k, it was possible to do it in O(N) but since it is sum>=k , I only have an O(NlogN) approach for it