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, non-empty sequence of elements within the array.
Function Signature
def longest_subarray(nums: list[int], limit: int) -> int:
Rules
-
Return only the length. Several subarrays can tie for the longest; they all have the same length.
-
A single element always qualifies, since its difference with itself is 0, so the answer is at least 1.
Constraints
-
1 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^9
-
0 <= limit <= 10^9
Examples
Input: nums = [8, 2, 4, 7], limit = 4
Output: 2
[2, 4] (difference 2) and [4, 7] (difference 3) qualify. [2, 4, 7] fails because 7 - 2 = 5 > 4, and every other subarray of length 3 or more contains both 8 and 2.
Input: nums = [10, 1, 2, 4, 7, 2], limit = 5
Output: 4
[2, 4, 7, 2] has maximum 7 and minimum 2, a difference of exactly 5, which the limit allows. Extending it to the left adds 1, and 7 - 1 = 6 is too large.
Input: nums = [4, 2, 2, 2, 4, 4, 2, 2], limit = 0
Output: 3
With a limit of 0 every element in the subarray must be equal, and the longest run of equal values is [2, 2, 2].