fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3.  
  4. using namespace std;
  5.  
  6. class Solution {
  7. public:
  8. int longestSubarray(vector<int>& nums, int limit) {
  9. int n = nums.size();
  10. int i = 0;
  11. int j = 0;
  12.  
  13. multiset<int> st;
  14.  
  15. int ans = 0;
  16.  
  17. while (j < n) {
  18. st.insert(nums[j]);
  19. while (*st.rbegin() - *st.begin() > limit) {
  20. st.erase(st.find(nums[i]));
  21. i++;
  22. }
  23.  
  24. ans = max(ans, j - i + 1);
  25. j++;
  26. }
  27.  
  28. return ans;
  29. }
  30. };
  31.  
  32. int main() {
  33. Solution sol;
  34. vector<int> nums = {8, 2, 4, 7};
  35. int limit = 4;
  36.  
  37. int result = sol.longestSubarray(nums, limit);
  38. cout << result << "\n";
  39.  
  40. return 0;
  41. }
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
2