eg. arr = {2,10, 3, 12, 5,4, 11, 8, 7, 6, 15}
Here we find 2 ranges for which all the integers in these ranges are present in the array.
namely: [2,8] and [10,12]
out of these [2,8] is the longer one. So we need to output that.
Basic Solution
First sort the array.
Have 3 integers - start, end and len. Initialize to 0. Have another variable "first" to point to the first element in the current set.
Loop the sorted array from start to end. Assign "first" to first element. Keep looping as long as the next element is contiguous. As soon as continuity breaks, subtract current number with "first". If it is more than "len", store "first" and current number in "start" and "end" respectively. Store the length calculated in "len". Continue this process.
You'll finally have the largest range in "start" and "end".
But Constraints is O(N)???
2 comments :
how about
1. finding min and max and constructing a count[min...max].
2.Traverse the array and set 1 count[a[i]] for every number.
2. The question is reduced to finding Longest contiguous sequences of '1'.
We may apply kadane's algo of largest contigous sum subse and keep track of start and end for sum>maxsum and reseting sum to 0 for every count[i]==0
not sure though.
@rajcools...your approach wont work test simple case when all array elements are non negative check here code for Largest Contiguous sum
https://ideone.com/WZDHF ..we have to think some other approach ..too busy right how so will try to think & put solution here asap :)
Post a Comment