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
| class MonotonicQueue { private: deque<int> queMin; deque<int> queMax; public: int min() { return queMin.front(); } int max() { return queMax.front(); } void push(int x) { while (!queMin.empty() && x < queMin.back()) queMin.pop_back(); queMin.push_back(x); while (!queMax.empty() && x > queMax.back()) queMax.pop_back(); queMax.push_back(x); } void popMin() { queMin.pop_front(); } void popMax() { queMax.pop_front(); } }; class Solution { public: int longestSubarray(vector<int>& nums, int limit) { MonotonicQueue q; int n = nums.size(), left = 0, right = 0, ans = 1; while (right < n) { q.push(nums[right]); while (left < n && q.max() - q.min() > limit) { if (q.min() == nums[left]) q.popMin(); if (q.max() == nums[left]) q.popMax(); ++left; } ans = max(ans, ++right - left); } return ans; } };
|