Creating findLength Function

// Returns length of the longest continuous subarray
static int findLength(int[] arr, int n)
{
    int max_len = 1;  // Initialize result
    for (int i = 0; i < n - 1; i++)
    {
        // Initialize min and max for all subarrays starting with i

        // Consider all subarrays starting with i and ending with j

        // Update min and max in this subarray if needed

        // If current subarray has all contiguous elements
        }
    }
    return max_len;  // Return result
}

The important thing to note in question is, it is given that all elements are distinct. If all elements are distinct, then a subarray has contiguous elements if and only if the difference between maximum and minimum elements in subarray is equal to the difference between last and first indexes of subarray. So the idea is to keep track of minimum and maximum element in every subarray.

for (int i = 0; i < n - 1; i++)
{
    // Initialize min and max for all subarrays starting with i
    int mn = arr[i], mx = arr[i];

    // Consider all subarrays starting with i and ending with j
    for (int j = i + 1; j < n; j++)
    {
        // Update min and max in this subarray if needed
        mn = Math.Min(mn, arr[j]);
        mx = Math.Max(mx, arr[j]);

        // If current subarray has all contiguous elements
        if ((mx - mn) == j - i)
            max_len = Math.Max(max_len, mx - mn + 1);
    }
}

results matching ""

    No results matching ""