classSolution { public: intlongestSubarray(vector<int>& nums, int limit){ int n = nums.size(); int left = 0, right = 0; int res = 0; priority_queue<int> bigHeap; priority_queue<int, vector<int>, greater<int>> smallHeap; unordered_map<int, int> bigDel, smallDel;
while (right < n) { if (bigHeap.empty() || (!bigHeap.empty() && bigHeap.top() - nums[right] <= limit && nums[right] - smallHeap.top() <= limit)) { bigHeap.push(nums[right]); smallHeap.push(nums[right]); right++; } else { res = max(res, right - left); bigDel[nums[left]]++; smallDel[nums[left]]++; left++; }
while (!bigHeap.empty() && bigDel[bigHeap.top()] > 0) { bigDel[bigHeap.top()]--; bigHeap.pop(); } while (!smallHeap.empty() && smallDel[smallHeap.top()] > 0) { smallDel[smallHeap.top()]--; smallHeap.pop(); } } res = max(res, right - left);
classSolution { public: intlongestSubarray(vector<int>& nums, int limit){ int n = nums.size(); int left = 0, right = 0, res = 0; deque<int> greaterQ, smallerQ;
while (right < n) { if (greaterQ.empty() || (!greaterQ.empty() && nums[right] - greaterQ.front() <= limit && smallerQ.front() - nums[right] <= limit)) { while (!greaterQ.empty() && nums[right] < greaterQ.back()) greaterQ.pop_back(); greaterQ.push_back(nums[right]); while (!smallerQ.empty() && nums[right] > smallerQ.back()) smallerQ.pop_back(); smallerQ.push_back(nums[right]); right++; } else { res = max(res, right - left); if (nums[left] == greaterQ.front()) greaterQ.pop_front(); if (nums[left] == smallerQ.front()) smallerQ.pop_front(); left++; } } res = max(res, right - left);