-
Notifications
You must be signed in to change notification settings - Fork 3
/
1438.cpp
26 lines (24 loc) · 884 Bytes
/
1438.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
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
// max q
deque<int> maxQ;
// min q
deque<int> minQ;
int res = 0;
int left = 0;
for (int right = 0; right < nums.size(); ++right) {
while (!maxQ.empty() && nums[right] >= nums[maxQ.back()]) maxQ.pop_back();
maxQ.push_back(right);
while (!minQ.empty() && nums[right] <= nums[minQ.back()]) minQ.pop_back();
minQ.push_back(right);
while (!maxQ.empty() && !minQ.empty() && nums[maxQ.front()] - nums[minQ.front()] > limit) {
left++;
while (maxQ.front() < left) maxQ.pop_front();
while (minQ.front() < left) minQ.pop_front();
}
res = max(res, right - left + 1);
}
return res;
}
};