Approach
Breadth-first search
For Longest Continuous Subarray with Absolute Diff Less Than or Equal to Limit, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 61 lines of Python from the credited upstream file longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 7class Solution(object):8 def longestSubarray(self, nums, limit):9 """10 :type nums: List[int]11 :type limit: int12 :rtype: int13 """14 max_dq, min_dq = collections.deque(), collections.deque()15 left = 016 for right, num in enumerate(nums):17 while max_dq and nums[max_dq[-1]] <= num:18 max_dq.pop()19 max_dq.append(right)20 while min_dq and nums[min_dq[-1]] >= num:21 min_dq.pop()22 min_dq.append(right)23 if nums[max_dq[0]]-nums[min_dq[0]] > limit:24 if max_dq[0] == left:25 max_dq.popleft()26 if min_dq[0] == left:27 min_dq.popleft()28 left += 1 29 return len(nums)-left30 31 323334import collections35 36 37class Solution2(object):38 def longestSubarray(self, nums, limit):39 """40 :type nums: List[int]41 :type limit: int42 :rtype: int43 """44 max_dq, min_dq = collections.deque(), collections.deque()45 result, left = 0, 046 for right, num in enumerate(nums):47 while max_dq and nums[max_dq[-1]] <= num:48 max_dq.pop()49 max_dq.append(right)50 while min_dq and nums[min_dq[-1]] >= num:51 min_dq.pop()52 min_dq.append(right)53 while nums[max_dq[0]]-nums[min_dq[0]] > limit: 54 if max_dq[0] == left:55 max_dq.popleft()56 if min_dq[0] == left:57 min_dq.popleft()58 left += 159 result = max(result, right-left+1)60 return result61