Given an unsorted array of positive integers, find the length of the longest subarray whose elements when sorted are continuous. Can you think of an O(n) solution?

Example:

{10, 5, 3, 1, 4, 2, 8, 7}, answer is 5.

{4, 5, 1, 5, 7, 6, 8, 4, 1}, answer is 5.

For the first example, the subarray {5, 3, 1, 4, 2} when sorted can form a continuous sequence 1,2,3,4,5, which are the longest.

For the second example, the subarray {5, 7, 6, 8, 4} is the result subarray.

I can think of a method which for each subarray, check if (maximum - minimum + 1) equals the length of that subarray, if true, then it is a continuous subarray. Take the longest of all. But it is O(n^2) and can not deal with duplicates.

Can someone gives a better method?

Edit
Report