#K2866. Longest Contiguous Subarray with Limited Absolute Difference
Longest Contiguous Subarray with Limited Absolute Difference
Longest Contiguous Subarray with Limited Absolute Difference
You are given an array of integers and an integer limit. Your task is to find the length of the longest contiguous subarray such that the absolute difference between any two elements in the subarray is at most limit
. Formally, for a subarray nums[i...j], it must satisfy
\( \max(\{nums[i], \ldots, nums[j]\}) - \min(\{nums[i], \ldots, nums[j]\}) \leq limit \).
This problem can be efficiently solved using a sliding window technique along with two deques to maintain the minimum and maximum values in the current window, achieving an overall time complexity of \(O(n)\).
inputFormat
The input is given via stdin in the following format:
- The first line contains two integers
n
andlimit
, wheren
is the number of elements in the array. - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
Output to stdout a single integer, the length of the longest contiguous subarray that satisfies the given condition.
## sample4 4
8 2 4 7
2
</p>