-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
48 lines (40 loc) · 1.4 KB
/
main.cpp
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
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
deque<int> inc, dec;
int result = 0;
for (int l = 0, r = 0; r < nums.size(); ++r) {
while (!inc.empty() && nums[inc.back()] > nums[r]) inc.pop_back();
inc.push_back(r);
while (!dec.empty() && nums[dec.back()] < nums[r]) dec.pop_back();
dec.push_back(r);
while (l <= r && nums[dec.front()] - nums[inc.front()] > limit) {
if (inc.front() == l) inc.pop_front();
if (dec.front() == l) dec.pop_front();
++l;
}
result = max(result, r - l + 1);
}
return result;
}
};
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
int result = 0;
deque<int> inc, dec;
for (int l = 0, r = 0; r < nums.size(); ++r) {
while (!inc.empty() && inc.back() > nums[r]) inc.pop_back();
inc.push_back(nums[r]);
while (!dec.empty() && dec.back() < nums[r]) dec.pop_back();
dec.push_back(nums[r]);
while (dec.front() - inc.front() > limit) {
if (inc.front() == nums[l]) inc.pop_front();
if (dec.front() == nums[l]) dec.pop_front();
++l;
}
result = max(result, r - l + 1);
}
return result;
}
};