class Solution {
public:
int longestSubarray(vector<int>& nums, int limit) {
deque<int> maxQueue, minQueue;
int res = 0;
for (int left = 0, right = 0; right < nums.size(); right++) {
while (!maxQueue.empty() && nums[maxQueue.back()] < nums[right]) {
maxQueue.pop_back();
}
while (!minQueue.empty() && nums[minQueue.back()] > nums[right]) {
minQueue.pop_back();
}
maxQueue.push_back(right);
minQueue.push_back(right);
while (!maxQueue.empty() && !minQueue.empty()
&& nums[maxQueue.front()] - nums[minQueue.front()] > limit) {
if (nums[left] == nums[maxQueue.front()]) {
maxQueue.pop_front();
} else if (nums[left] == nums[minQueue.front()]) {
minQueue.pop_front();
}
left++;
}
res = max(res, right - left + 1);
}
return res;
}
};