#C1649. 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 difference between the maximum element and the minimum element in the subarray is at most limit. In other words, if a subarray has maximum value M and minimum value m, then the subarray is valid if
$$M - m \leq limit.$$
You need to output the length of the longest valid subarray.
Example 1: For the array [8, 2, 4, 7] with limit = 4, the longest valid subarray is [2, 4] with length 2.
Example 2: For the array [10, 1, 2, 4, 7, 2] with limit = 5, the longest valid subarray is [1, 2, 4, 7] with length 4.
Example 3: For the array [4, 2, 2, 2, 4, 4, 2, 2] with limit = 0, the longest valid subarray is [2, 2, 2] with length 3.
inputFormat
The input is read from stdin and has the following format:
- An integer n denoting the number of elements in the array.
- n space-separated integers representing the array.
- An integer limit representing the maximum allowed absolute difference between the maximum and minimum elements in any valid subarray.
For example:
4 8 2 4 7 4
outputFormat
Output a single integer to stdout, which is the length of the longest contiguous subarray satisfying the condition.
For example, the output for the sample input above is:
2## sample
4
8 2 4 7
4
2