Skip to content

Commit 217a980

Browse files
authored
Create Solution3.cpp
1 parent 5eae863 commit 217a980

File tree

1 file changed

+31
-0
lines changed
  • solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution {
2+
public:
3+
int longestSubarray(vector<int>& nums, int limit) {
4+
deque<int> max_q;
5+
deque<int> min_q;
6+
int n = nums.size();
7+
int l = 0;
8+
9+
for (int r = 0; r < n; ++r) {
10+
while (!max_q.empty() && nums[max_q.back()] < nums[r]) {
11+
max_q.pop_back();
12+
}
13+
while (!min_q.empty() && nums[min_q.back()] > nums[r]) {
14+
min_q.pop_back();
15+
}
16+
max_q.push_back(r);
17+
min_q.push_back(r);
18+
19+
if (nums[max_q.front()] - nums[min_q.front()] > limit) {
20+
++l;
21+
if (max_q.front() < l) {
22+
max_q.pop_front();
23+
}
24+
if (min_q.front() < l) {
25+
min_q.pop_front();
26+
}
27+
}
28+
}
29+
return n - l;
30+
}
31+
};

0 commit comments

Comments
 (0)