# 1438. 绝对差不超过限制的最长连续子数组
# 题目
给你一个整数数组 nums ,和一个表示限制的整数 limit,请你返回最长连续子数组的长度,该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit 。
如果不存在满足条件的子数组,则返回 0 。
# 题解
# 滑动窗口
只需要统计窗口内到最大值和最小值即可确定是否满足条件
用两个单调队列来处理
/**
* @param {number[]} nums
* @param {number} limit
* @return {number}
*/
var longestSubarray = function(nums, limit) {
const qMax = [];
const qMin = [];
const n = nums.length;
let l = (r = 0),
ret = 0;
while (r < n) {
while (qMax.length && qMax[qMax.length - 1] < nums[r]) {
qMax.pop();
}
while (qMin.length && qMin[qMin.length - 1] > nums[r]) {
qMin.pop();
}
qMax.push(nums[r]);
qMin.push(nums[r]);
while (qMax.length && qMin.length && qMax[0] - qMin[0] > limit) {
if (nums[l] == qMin[0]) qMin.shift();
if (nums[l] == qMax[0]) qMax.shift();
l++;
}
ret = Math.max(ret, r - l + 1);
r++;
}
return ret;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33