forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
61 lines (59 loc) · 1.92 KB
/
longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.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
49
50
51
52
53
54
55
56
57
58
59
60
61
// Time: O(n)
// Space: O(n)
class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
deque<int> max_dq, min_dq;
int left = 0;
for (int right = 0; right < nums.size(); ++right) {
while (!max_dq.empty() && nums[max_dq.back()] <= nums[right]) {
max_dq.pop_back();
}
max_dq.emplace_back(right);
while (!min_dq.empty() && nums[min_dq.back()] >= nums[right]) {
min_dq.pop_back();
}
min_dq.emplace_back(right);
if (nums[max_dq[0]] - nums[min_dq[0]] > limit) {
if (max_dq[0] == left) {
max_dq.pop_front();
}
if (min_dq[0] == left) {
min_dq.pop_front();
}
++left; // advance left by one to not count in result
}
}
return nums.size() - left;
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
int longestSubarray(vector<int>& nums, int limit) {
deque<int> max_dq, min_dq;
int result = 0, left = 0;
for (int right = 0; right < nums.size(); ++right) {
while (!max_dq.empty() && nums[max_dq.back()] <= nums[right]) {
max_dq.pop_back();
}
max_dq.emplace_back(right);
while (!min_dq.empty() && nums[min_dq.back()] >= nums[right]) {
min_dq.pop_back();
}
min_dq.emplace_back(right);
while (nums[max_dq[0]] - nums[min_dq[0]] > limit) { // both always exist "right" element
if (max_dq[0] == left) {
max_dq.pop_front();
}
if (min_dq[0] == left) {
min_dq.pop_front();
}
++left;
}
result = max(result, right - left + 1);
}
return result;
}
};