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: 3Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^90 <= limit <= 10^9题目的意思是:给你一个数组,找出绝对值距离都小于或等于limit的子数组,返回子数组长度的最大值。这道题我暴力破解了一下,发现超时了,原因是我每次更新的时候都求最小值和最大值,如果加入一个判断条件,就可以缩小计算量,在进行跳转的时候判断当前的值是否是最小值或者最大值,如果是就需要重新进行求最小值或者最大值,否则就直接跳过。
[LeetCode] Py Detailed Easy Sol: Explaination, Thinking Approach, Commented