[leetcode] 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

    科技2024-09-28  17

    Description

    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 <= 10^51 <= nums[i] <= 10^90 <= limit <= 10^9

    分析

    题目的意思是:给你一个数组,找出绝对值距离都小于或等于limit的子数组,返回子数组长度的最大值。这道题我暴力破解了一下,发现超时了,原因是我每次更新的时候都求最小值和最大值,如果加入一个判断条件,就可以缩小计算量,在进行跳转的时候判断当前的值是否是最小值或者最大值,如果是就需要重新进行求最小值或者最大值,否则就直接跳过。

    代码

    class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: left=0 n=len(nums) l=0 r=1 maxVal=nums[0] minVal=nums[0] res=1 while(l<r and r<n): maxVal=max(maxVal,nums[r]) minVal=min(minVal,nums[r]) if(maxVal-minVal<=limit): res=max(res,r-l+1) else: if(nums[l]==maxVal): maxVal=max(nums[l+1:r+1]) if(nums[l]==minVal): minVal=min(nums[l+1:r+1]) l+=1 r+=1 return res

    参考文献

    [LeetCode] Py Detailed Easy Sol: Explaination, Thinking Approach, Commented

    Processed: 0.016, SQL: 8