Skip to content

Commit afb2553

Browse files
authored
Create 1438. Longest Continuous Subarray With Absolute Diff Less Than… (#511)
2 parents 0c032c0 + 9e84e93 commit afb2553

File tree

1 file changed

+35
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)