Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit - Problem
Given an array of integers nums and an integer limit, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is less than or equal to limit.
A subarray is a contiguous part of an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [8,2,4,7], limit = 4
›
Output:
2
💡 Note:
The longest subarray is [2,4] with absolute difference |4-2| = 2 ≤ 4. Length is 2.
Example 2 — Larger Limit
$
Input:
nums = [10,1,2,4,7,2], limit = 5
›
Output:
4
💡 Note:
The longest subarray is [2,4,7,2] with max difference |7-2| = 5 ≤ 5. Length is 4.
Example 3 — Single Element
$
Input:
nums = [4,2,2,2,4,4,2,2], limit = 0
›
Output:
3
💡 Note:
The longest subarray with all equal elements is [2,2,2]. Length is 3.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ limit ≤ 109
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [8,2,4,7] with limit = 4
2
Process
Find longest subarray where max - min ≤ 4
3
Output
Return length of longest valid subarray
Key Takeaway
🎯 Key Insight: Use sliding window with monotonic deques to efficiently track min/max values
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code