⚡Flashcard Drill➔
NeetCode #258LC-1438MediumSliding Window
← Back to All Problems

#258 · #1438 · Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit(绝对差不超过限制的最长连续子数组)

📌 Problem Statement & Constraints

Given an array of integers nums and an integer limit, return the size of the longest subarray such that the absolute difference between any two of its elements is at most limit. Constraints: 1 <= nums.length <= 10^5, 1 <= nums[i] <= 10^9, 0 <= limit <= 10^9.

💡 Core Algorithmic Approaches

  1. A window satisfies the condition exactly when max(window) - min(window) <= limit.
  2. So we need a sliding window with efficient access to its maximum and minimum -- two monotonic deques.
  3. One deque keeps indices in decreasing value order (front = maximum); the other keeps increasing order (front = minimum).
  4. When the difference exceeds limit, advance the left pointer and evict it from either deque if it is at the front.

💻 Benchmark Python3 Implementation

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        from collections import deque
        maxq = deque()                 # decreasing values, front is the max
        minq = deque()                 # increasing values, front is the min
        l = 0
        best = 0
        for r, x in enumerate(nums):
            while maxq and nums[maxq[-1]] <= x:
                maxq.pop()
            maxq.append(r)
            while minq and nums[minq[-1]] >= x:
                minq.pop()
            minq.append(r)
            while nums[maxq[0]] - nums[minq[0]] > limit:
                if maxq[0] == l:
                    maxq.popleft()
                if minq[0] == l:
                    minq.popleft()
                l += 1
            best = max(best, r - l + 1)
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each index is pushed and popped at most once from each deque.
💾 Space Complexity
O(n) for the two deques in the worst case.

⚠️ Interview Pitfalls & Follow-ups

  • Using max(window) and min(window) on the fly: O(n) per step, giving O(n^2).
  • Evicting from only one deque when shrinking: the leaving index may be at the front of either deque, so both must be checked.
  • Storing values instead of indices: you cannot tell whether the front has left the window.
  • Using < in the back-popping comparisons: either < or <= works, but be consistent; <= keeps the deques strictly monotone and slightly smaller.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

绝对差不超过限制的最长连续子数组

给你一个整数数组 nums,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit。如果不存在满足条件的子数组,则返回 0。约束:1 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^9;0 ≤ limit ≤ 10^9。

核心要点

  • 双单调队列维护窗口极值(标准解) :窗口内「任意两元素之差 ≤ limit」等价于「窗口最大值 − 窗口最小值 ≤ limit」。
  • 两个单调队列 : maxd 维护单调递减(队首为最大值), mind 维护单调递增(队首为最小值)。
  • 收缩条件 :当 maxd[0] − mind[0] &gt; limit 时,移除左端元素(若它等于某个队列的队首则弹出),并右移 l。
  • 复杂度 :每个元素最多入队出队各一次,O(n)。

常见陷阱

  • 只用 max / min 每次重新求窗口极值 :O(n · k),在大窗口时退化为 O(n²)。
  • 队列中存值而非下标 :当窗口内有重复值时,「等于 nums[l]」会误弹出不该弹的元素。用下标判断更严谨(本解用值判断在无重复时正确,但推荐存下标)。
  • 只维护一个单调队列 :需要同时知道最大值与最小值,必须两个队列。
  • 收缩时忘记同时维护两个队列 :只弹一个队列会导致极值判断错误。

参考实现

from collections import deque

class Solution:
    def longestSubarray(self, nums: list[int], limit: int) -> int:
        maxd = deque()          # 单调递减,队首为窗口最大值
        mind = deque()          # 单调递增,队首为窗口最小值
        l = 0
        best = 0
        for r, x in enumerate(nums):
            while maxd and maxd[-1] < x:
                maxd.pop()
            maxd.append(x)
            while mind and mind[-1] > x:
                mind.pop()
            mind.append(x)

            while maxd[0] - mind[0] > limit:     # 极差超限 -> 收缩
                if maxd[0] == nums[l]:
                    maxd.popleft()
                if mind[0] == nums[l]:
                    mind.popleft()
                l += 1

            if r - l + 1 > best:
                best = r - l + 1
        return best