fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <deque>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int longestSubarray(vector<int>& nums, int limit) {
  9. deque<int> max_d, min_d;
  10. int i = 0, res = 0;
  11. for (int j = 0; j < nums.size(); ++j) {
  12. while (!max_d.empty() && nums[j] > max_d.back()) max_d.pop_back();
  13. while (!min_d.empty() && nums[j] < min_d.back()) min_d.pop_back();
  14. max_d.push_back(nums[j]);
  15. min_d.push_back(nums[j]);
  16.  
  17. while (max_d.front() - min_d.front() > limit) {
  18. if (max_d.front() == nums[i]) max_d.pop_front();
  19. if (min_d.front() == nums[i]) min_d.pop_front();
  20. i++;
  21. }
  22. res = max(res, j - i + 1);
  23. }
  24. return res;
  25. }
  26.  
  27. int main() {
  28. vector<int> test = {4, 2, 3, 6, 2, 2, 3, 2, 7};
  29. int limit = 1;
  30. cout << "Longest N-stable: " << longestSubarray(test, limit) << endl; // Output: 4
  31. return 0;
  32. }
Success #stdin #stdout 0.01s 5320KB
stdin
Standard input is empty
stdout
Longest N-stable: 4