Length of the largest subarray with contiguous elements

Given an array of integers, find length of the longest subarray which contains numbers that can be arranged in a continuous sequence.

In the previous post, we have discussed a solution that assumes that elements in given array are distinct. Here we discuss a solution that works even if the input array has duplicates.

Examples:

Input:  arr[] = {10, 12, 11};
Output: Length of the longest contiguous subarray is 3

Input:  arr[] = {10, 12, 12, 10, 10, 11, 10};
Output: Length of the longest contiguous subarray is 2 
class Solution {
    public int maxSubArray(int[] arr) {
        // Procedure
        // Go through all the sub-arrays, find min and max
        // if max-min==length of subarray, then it is a possible answer
        int maxLen = 0;
        for (int i = 0; i < arr.length; i++) {
            int min = Integer.MAX_VALUE, max = Integer.MAX_VALUE;
            Set<Integer> set = new HashSet<>();
            for (int j = i; j < arr.length; i++) {
                // If duplicate elements exists in this subarray, then we cannot
                // consider this and the following subarrays for our answer
                // because we want continous elements
                if (set.contains(arr[j]))
                    break;
                set.add(arr[j]);
                min = Math.min(min, arr[j]);
                max = Math.max(max, arr[j]);
                if (max - min == j - i)
                    maxLen = Math.max(maxLen, j - i + 1);
            }
        }
        return maxLen;
    }
}

Last updated