[LeetCode in Python] 5402 (M) longest continuous subarray with absolute diff less than or equal to l

Posted ET民工[源自火星]

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode in Python] 5402 (M) longest continuous subarray with absolute diff less than or equal to l相关的知识,希望对你有一定的参考价值。

题目

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

给你一个整数数组 nums ,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit 。
如果不存在满足条件的子数组,则返回 0 。

示例 1:

输入:nums = [8,2,4,7], limit = 4
输出:2

解释:所有子数组如下:
[8] 最大绝对差 |8-8| = 0 <= 4.
[8,2] 最大绝对差 |8-2| = 6 > 4.
[8,2,4] 最大绝对差 |8-2| = 6 > 4.
[8,2,4,7] 最大绝对差 |8-2| = 6 > 4.
[2] 最大绝对差 |2-2| = 0 <= 4.
[2,4] 最大绝对差 |2-4| = 2 <= 4.
[2,4,7] 最大绝对差 |2-7| = 5 > 4.
[4] 最大绝对差 |4-4| = 0 <= 4.
[4,7] 最大绝对差 |4-7| = 3 <= 4.
[7] 最大绝对差 |7-7| = 0 <= 4.
因此,满足题意的最长子数组的长度为 2 。

示例 2:

输入:nums = [10,1,2,4,7,2], limit = 5
输出:4

解释:满足题意的最长子数组是 [2,4,7,2],其最大绝对差 |2-7| = 5 <= 5 。

示例 3:

输入:nums = [4,2,2,2,4,4,2,2], limit = 0
输出:3
?
提示:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
0 <= limit <= 10^9

解题思路

  • 两个单调队列,一个递增,一个递减,存数组元素的下标
  • 双指针,左指针初始为0,右指针遍历数组
    • 每当右指针前进1,就更新两个单调队列
    • 反复查看最大值和最小值的差,如果不满足限制,就将左指针右移1
      • 然后检查单调队列的极值是否超出了窗口范围,如果超了就扔掉

代码

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

        # - monotonic queue, decrease
        maxq = collections.deque()

        # - monotonic queue, increase
        minq = collections.deque()

        # - window left edge index
        left = 0

        # - window right edge index
        for i,n in enumerate(nums):
            # - update maxq
            while maxq and nums[maxq[-1]] < n: maxq.pop()
            maxq.append(i)

            # - update minq
            while minq and nums[minq[-1]] > n: minq.pop()
            minq.append(i)

            # - check limit
            while maxq and minq and (nums[maxq[0]]-nums[minq[0]]) > limit:
                left += 1

                # - check if maxq and minq has element out of window
                if maxq[0] < left: maxq.popleft()
                if minq[0] < left: minq.popleft()

            res = max(res, i-left+1)

        return res



















以上是关于[LeetCode in Python] 5402 (M) longest continuous subarray with absolute diff less than or equal to l的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode算法题python解法:24. Swap Nodes in Pairs

LeetCode 467 - Unique Substrings in Wraparound String - Medium (Python)

[LeetCode in Python] 79 (M) word search 单词搜索

LeetCode算法题python解法:25. Reverse Nodes in k-Group

[LeetCode&Python] Problem 700. Search in a Binary Search Tree

Python 解LeetCode:33. Search in Rotated Sorted Array