Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++


Suppose we have an array of integers called nums and an integer limit, we have to find the size of the longest non-empty subarray such that the absolute difference between any two items of this subarray is less than or equal to the given limit.

So, if the input is like nums = [8,2,4,7], limit = 4, then the output will be 2, this is because −

  • [8] so |8-8| = 0 <= 4.

  • [8,2] so |8-2| = 6 > 4.

  • [8,2,4] so |8-2| = 6 > 4.

  • [8,2,4,7] so |8-2| = 6 > 4.

  • [2] so |2-2| = 0 <= 4.

  • [2,4] so |2-4| = 2 <= 4.

  • [2,4,7] so |2-7| = 5 > 4.

  • [4] so |4-4| = 0 <= 4.

  • [4,7] so |4-7| = 3 <= 4.

  • [7] so |7-7| = 0 <= 4.

Finally, the size of the longest subarray is 2.

To solve this, we will follow these steps −

  • ret := 0, i := 0, j := 0

  • Define one deque maxD and another deque minD

  • n := size of nums

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • while (not maxD is empty and last element of maxD < nums[i]), do −

      • delete last element from maxD

    • while (not minD is empty and last element of minD > nums[i]), do −

      • delete last element from minD

    • insert nums[i] at the end of maxD

    • insert nums[i] at the end of minD

    • while (first element of maxD - first element of minD) > k, do −

      • if nums[j] is same as first element of maxD, then−

        • delete front element from maxD

      • if nums[j] is same as first element of minD, then −

        • delete front element from minD

      • (increase j by 1)

    • ret := maximum of ret and (i - j + 1)

  • return ret

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int longestSubarray(vector<int>& nums, int k) {
      int ret = 0;
      int i = 0;
      int j = 0;
      deque<int> maxD;
      deque<int> minD;
      int n = nums.size();
      for (int i = 0; i < n; i++) {
         while (!maxD.empty() && maxD.back() < nums[i])
            maxD.pop_back();
         while (!minD.empty() && minD.back() > nums[i])
            minD.pop_back();
         maxD.push_back(nums[i]);
         minD.push_back(nums[i]);
         while (maxD.front() - minD.front() > k) {
            if (nums[j] == maxD.front())
               maxD.pop_front();
            if (nums[j] == minD.front())
               minD.pop_front();
            j++;
         }
         ret = max(ret, i - j + 1);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<int> v = {7,8,2,4};
   cout << (ob.longestSubarray(v, 4));
}

Input

{7,8,2,4}, 4

Output

2

Updated on: 17-Nov-2020

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements