Advertisement
nikunjsoni

1438

Apr 17th, 2021
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.69 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int longestSubarray(vector<int>& A, int limit) {
  4.         deque<int> maxd, mind;
  5.         int i = 0, j;
  6.         int ans = 0;
  7.         for (j = 0; j < A.size(); ++j) {
  8.             while(!maxd.empty() && A[j] > maxd.back()) maxd.pop_back();
  9.             while(!mind.empty() && A[j] < mind.back()) mind.pop_back();
  10.             maxd.push_back(A[j]);
  11.             mind.push_back(A[j]);
  12.             while(maxd.front() - mind.front() > limit){
  13.                 if(maxd.front() == A[i]) maxd.pop_front();
  14.                 if(mind.front() == A[i]) mind.pop_front();
  15.                 ++i;
  16.             }
  17.             ans = max(ans, j-i+1);
  18.         }
  19.         return ans;
  20.     }
  21. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement