-
Notifications
You must be signed in to change notification settings - Fork 7
/
1438.js
95 lines (92 loc) · 2.84 KB
/
1438.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const longestSubarray = (nums, limit) => {
let ret = 0;
for (let left = 0, right = 0, cur = 0, min = nums[0], max = nums[0]; right < nums.length; ++right) {
while (nums[right] - min > limit || max - nums[right] > limit) {
if (nums[left] === min || nums[left] === max) {
min = 10 ** 9;
max = 0;
for (let i = left + 1; i <= right; ++i) {
nums[i] < min && (min = nums[i]);
nums[i] > max && (max = nums[i]);
}
}
--cur;
++left;
}
nums[right] < min && (min = nums[right]);
nums[right] > max && (max = nums[right]);
++cur > ret && (ret = cur);
}
return ret;
};
const longestSubarray = (nums, limit) => {
const maxQue = [];
const minQue = [];
let maxTop = -1, minTop = -1, max = 0;
for (let left = -1, right = 0; right < nums.length; ++right) {
const val = nums[right];
while (maxTop >= 0 && val > maxQue[maxTop]) --maxTop;
while (minTop >= 0 && val < minQue[minTop]) --minTop;
maxQue[++maxTop] = val;
minQue[++minTop] = val;
if (maxQue[0] - minQue[0] <= limit) {
right - left > max && (max = right - left);
} else {
while (maxQue[0] - minQue[0] > limit) {
++left;
if (maxQue[0] === nums[left]) {
maxQue.shift();
--maxTop;
}
if (minQue[0] === nums[left]) {
minQue.shift();
--minTop;
}
}
}
}
return max;
};
const longestSubarray = (nums, limit) => {
const maxQue = [];
const minQue = [];
let maxTop = -1, minTop = -1;
let maxBottom = 0, minBottom = 0;
let max = 0;
for (let left = -1, right = 0; right < nums.length; ++right) {
const val = nums[right];
while (maxTop >= maxBottom && val > maxQue[maxTop]) --maxTop;
while (minTop >= minBottom && val < minQue[minTop]) --minTop;
maxQue[++maxTop] = val;
minQue[++minTop] = val;
if (maxQue[maxBottom] - minQue[minBottom] <= limit) {
right - left > max && (max = right - left);
} else {
while (maxQue[maxBottom] - minQue[minBottom] > limit) {
++left;
maxQue[maxBottom] === nums[left] && ++maxBottom;
minQue[minBottom] === nums[left] && ++minBottom;
}
}
}
return max;
};
const longestSubarray = (nums, limit) => {
const maxQue = [];
const minQue = [];
let maxTop = -1, minTop = -1, left = -1;
let maxBottom = 0, minBottom = 0;
for (let right = 0; right < nums.length; ++right) {
const val = nums[right];
while (maxTop >= maxBottom && val > maxQue[maxTop]) --maxTop;
while (minTop >= minBottom && val < minQue[minTop]) --minTop;
maxQue[++maxTop] = val;
minQue[++minTop] = val;
if (maxQue[maxBottom] - minQue[minBottom] > limit) {
++left;
maxQue[maxBottom] === nums[left] && ++maxBottom;
minQue[minBottom] === nums[left] && ++minBottom;
}
}
return nums.length - left - 1;
};