Imagine you're a quality control manager at a manufacturing plant. You need to find the longest continuous sequence of product measurements where the difference between the highest and lowest values doesn't exceed your quality tolerance limit.
Given an array of integers nums representing measurements and an integer limit representing your tolerance threshold, return the size of the longest non-empty subarray such that the absolute difference between any two elements of this subarray is at most limit.
In other words, for a valid subarray, max(subarray) - min(subarray) ⤠limit.
Example: If nums = [8,2,4,7] and limit = 4, the longest valid subarray is [2,4] with length 2, because |4-2| = 2 ⤠4.
Input & Output
Visualization
Time & Space Complexity
Two nested loops - outer loop for starting position, inner loop to extend subarray
Only using variables to track max, min, and result length
Constraints
- 1 ⤠nums.length ⤠105
- 1 ⤠nums[i] ⤠109
- 0 ⤠limit ⤠109
- Follow up: Can you solve this in O(n) time?