Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

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`.

30:00

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
medium
Free written solution
Topics
Companies

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.

Example 1:
Input: {"nums":[8,2,4,7],"limit":4}
Output: 2
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • 1≤nums[i]≤1091 \leq \text{nums}[i] \leq 10^9

  • 0≤limit≤1090 \leq \text{limit} \leq 10^9

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[8,2,4,7],"limit":4}

Keep two deques of indices: the front of the max deque is the window's largest value and the front of the min deque is its smallest. The window is valid while max - min <= 4.

nums as bars

80214273

max · min · dashed band: every bar in the window must end inside it

max deque (values fall front to back)

front

back

min deque (values rise front to back)

front

back

max - min

-

window

-

best

0

Variables
VariableValue
left0
best0
limit4
DepthFunction Call
Stack empty
0/26