#K46427. Longest Consecutive Subarray Length
Longest Consecutive Subarray Length
Longest Consecutive Subarray Length
Problem Statement:
Given an array of integers, determine the length of the longest contiguous subarray such that its elements can be rearranged to form a sequence of consecutive integers. A subarray is a contiguous part of the array, and the sequence formed must consist of distinct numbers. In other words, for a subarray from index l to r, if the maximum element minus the minimum element equals r - l
and no number repeats, then the elements can be arranged to form a consecutive sequence.
Detailed Explanation:
For any contiguous subarray a[l...r]
, the necessary and sufficient condition for its elements to be rearranged as consecutive integers is:
[ max(a[l...r]) - min(a[l...r]) = r - l ]
Along with the additional constraint that all elements in the subarray must be unique. Your task is to find the maximum length of such a subarray within the given array.
Example:
- For the array [1, 2, 2, 3, 4, 1], the longest contiguous subarray that can be rearranged into a consecutive sequence is of length 4.
- For the array [10, 12, 11, 14, 13], the longest valid subarray is the entire array (length 5).
- For the array [1, 5, 7], no subarray longer than 1 meets the criteria.
inputFormat
The input consists of two lines:
- The first line contains an integer
n
, the number of elements in the array. - The second line contains
n
space-separated integers representing the array.
outputFormat
Output a single integer representing the length of the longest contiguous subarray that can be rearranged to form a sequence of consecutive integers.
## sample6
1 2 2 3 4 1
4