#K2866. Longest Contiguous Subarray with Limited Absolute Difference

    ID: 24832 Type: Default 1000ms 256MiB

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:

  1. The first line contains two integers n and limit, where n is the number of elements in the array.
  2. 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.

## sample
4 4
8 2 4 7
2

</p>