Leetcode 1549 Solution

This article provides solution to leetcode question 1549 (longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit)

https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit

Solution

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        l, r = 0, 0

        q1 = collections.deque()
        q2 = collections.deque()

        ans = 0
        while r < len(nums):
            while q1 and nums[q1[-1]] < nums[r]:
                q1.pop()
            q1.append(r)

            while q2 and nums[q2[-1]] > nums[r]:
                q2.pop()
            q2.append(r)

            while nums[q1[0]] - nums[q2[0]] > limit:
                if q1[0] <= l:
                    q1.popleft()
                if q2[0] <= l:
                    q2.popleft()
                l += 1

            ans = max(ans, r - l + 1)

            r += 1

        return ans