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

网友投稿 296 2022-08-26

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

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 = 4Output: 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 = 5Output: 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 = 0Output: 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

参考文献

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:[leetcode] 1014. Best Sightseeing Pair
下一篇:诱导消费、夸大收益、炒停售,揭秘保险“套路”营销!
相关文章

 发表评论

暂时没有评论,来抢沙发吧~