#C13345. Longest Subarray with Limit

    ID: 42873 Type: Default 1000ms 256MiB

Longest Subarray with Limit

Longest Subarray with Limit

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 its maximum and minimum elements is less than or equal to limit.

The problem can be mathematically formulated as finding the maximum integer L such that there exists an index i with a subarray nums[i], nums[i+1], ..., nums[i+L-1] satisfying $$\max(nums[i...i+L-1]) - \min(nums[i...i+L-1]) \leq limit.$$

This problem requires a sliding window approach combined with a double-ended queue (deque) to keep tracking of the current window's minimum and maximum values efficiently.

inputFormat

The input consists of two lines:

  • The first line contains two integers n and limit, where n denotes the number of elements in the array.
  • The second line contains n space-separated integers representing the array elements.

outputFormat

Output a single integer indicating the length of the longest contiguous subarray that meets the condition.

## sample
4 4
8 2 4 7
2

</p>