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