Skip to content

1549. Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Array Queue Sliding Window Heap (Priority Queue) Ordered Set Monotonic Queue

Problem - Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Medium

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 
Explanation: All subarrays are: 
[8] with maximum absolute diff |8-8| = 0 <= 4.
[8,2] with maximum absolute diff |8-2| = 6 > 4. 
[8,2,4] with maximum absolute diff |8-2| = 6 > 4.
[8,2,4,7] with maximum absolute diff |8-2| = 6 > 4.
[2] with maximum absolute diff |2-2| = 0 <= 4.
[2,4] with maximum absolute diff |2-4| = 2 <= 4.
[2,4,7] with maximum absolute diff |2-7| = 5 > 4.
[4] with maximum absolute diff |4-4| = 0 <= 4.
[4,7] with maximum absolute diff |4-7| = 3 <= 4.
[7] with maximum absolute diff |7-7| = 0 <= 4. 
Therefore, the size of the longest subarray is 2.

Example 2:

Input: nums = [10,1,2,4,7,2], limit = 5
Output: 4 
Explanation: The subarray [2,4,7,2] is the longest since the maximum absolute diff is |2-7| = 5 <= 5.

Example 3:

Input: nums = [4,2,2,2,4,4,2,2], limit = 0
Output: 3

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 0 <= limit <= 109

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        # sorted_list = SortedList()
        # result = j = 0
        # for i, val in enumerate(nums):
        #     sorted_list.add(val)
        #     while sorted_list[-1] - sorted_list[0] > limit:
        #         sorted_list.remove(nums[j])
        #         j += 1
        #     result = max(result, i - j + 1)
        # return result

        min_queue = Deque()
        max_queue = Deque()
        left = 0
        n = len(nums)
        for right, val in enumerate(nums):
            while max_queue and nums[max_queue[-1]] < val:
                max_queue.pop()
            while min_queue and nums[min_queue[-1]] > val:
                min_queue.pop()

            min_queue.append(right)
            max_queue.append(right)

            if nums[max_queue[0]] - nums[min_queue[0]] > limit:
                left += 1
                if max_queue[0] < left:
                    max_queue.popleft()
                if min_queue[0] < left:
                    min_queue.popleft()

        return n - left

Submission Stats:

  • Runtime: 119 ms (99.05%)
  • Memory: 27.1 MB (40.52%)