Longest Continuous Subarray Within Limit (Deque Optimization)

Given an integer array and a limit, return the length of the longest contiguous subarray where the absolute difference between any two elements is at most the limit. Pattern focus: Deque Window Optimization. Two monotonic deques let you maintain the max and min of the active window in O(1) amortized time.

Input Format

nums = array of integers, limit = maximum allowed difference

Output Format

length of the longest valid subarray

Constraints

  • 1 <= input size <= 10^5
  • -10^9 <= numeric values <= 10^9
  • nums, limit must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

nums = [8,2,4,7]
limit = 4

Output:

2

Explanation:

The longest valid subarray has length 2.

Example 2:

Input:

nums = [10,1,2,4,7,2]
limit = 5

Output:

4

Explanation:

The subarray [2,4,7,2] is the longest valid one.

Loading...
Longest Continuous Subarray Within Limit…