All problems

Problem 506

Longest Subarray with Limited Difference

Medium · 20 pts · Array, Sliding Window, Monotonic Queue

Problem

Find the length of the longest block of consecutive elements in which the difference between the largest and the smallest element is at most a given limit. A single element always qualifies. Use a sliding window and two monotonic deques, one tracking the window maximum and one the minimum; shrink the window from the left while the difference is too large.

Input

The first line contains N and the limit. The second line contains N integers.

Output

Print the length of the longest qualifying subarray.

Constraints

1 <= N <= 100000; 1 <= A[i] <= 1000000000; 0 <= limit <= 1000000000

Example input

4 4
8 2 4 7

Example output

2

Explanation

In 8 2 4 7 with limit 4, the block 2 4 has difference 2 and the block 4 7 has difference 3, but every block of three elements has a difference above 4. So the answer is 2.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Count Subarrays with K Odd Numbers Next: Max Chunks to Make Sorted