Length of the largest subarray with contiguous elements

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

Examples:

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

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

Input:  arr[] = {1, 56, 58, 57, 90, 92, 94, 93, 91, 45};
Output: Length of the longest contiguous subarray is 5
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;
            for (int j = i; j < arr.length; i++) {
                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