Longest subarray with absolute difference between elements less than or equal to K using Heaps

Given an array arr[] of N integers and an integer K, our task is to find the length of the longest subarray such that for all possible pairs in the subarray absolute difference between elements is less than or equal to K.
Examples:

Input: arr[] = {2, 4, 5, 5, 5, 3, 1}, K = 0 
Output:
Explanation: 
The possible subarray with difference in elements as 0 is {5, 5, 5} whose length is 3. Hence the output is 3.

Input: arr[] = {1, 2, 3, 6, 7}, K = 2 
Output:
Explanation: 
The possible subarray with difference in elements at most 2 is {1, 2, 3} whose length is 3. Hence the output is 3.

Naive Approach: 
To solve the problem mentioned above the naive method is to use The Brute Force approach that is to generate all the possible subarray of the given array and check if the difference between the maximum and minimum element of the subarray is at most K or not. If it is, then update the length of the current subarray with the maximum length. Print the maximum length of the subarray after all the operations.

Below is the implementation of the above approach:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find the Longest subarray
// of the given array with absolute difference between
// elements less than or equal to integer K
#include <bits/stdc++.h>
using namespace std;
 
int computeLongestSubarray(int arr[], int k, int n)
{
     
    // maxLength is 1 because k >= 0,
    // a single element, subarray will always
    // have absolute difference zero
    int maxLength = 1;
 
    // Check for all possible subarrays
    for(int i = 0; i < n; i++)
    {
         
        // Initalization of minimum &
        // maximum of current subarray
        int minOfSub = arr[i];
        int maxOfSub = arr[i];
 
        for(int j = i + 1; j < n; j++)
        {
 
            // Update the values for minimum & maximum
            if (arr[j] > maxOfSub)
                maxOfSub = arr[j];
 
            if (arr[j] < minOfSub)
                minOfSub = arr[j];
 
            // Check if current subarray satisfies
            // the given condition
            if ((maxOfSub - minOfSub) <= k)
            {
                int currLength = j - i + 1;
 
                // Update the value for maxLength
                if (maxLength < currLength)
                    maxLength = currLength;
            }
        }
    }
 
    // Return the final result
    return maxLength;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 6, 7 };
 
    int k = 2;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    int maxLength = computeLongestSubarray(arr, k, n);
     
    cout << (maxLength);
}
 
// This code is contributed by chitranayal

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the Longest subarray
// of the given array with absolute difference between
// elements less than or equal to integer K
 
class GFG {
    public static int computeLongestSubarray(int arr[],
                                                int k)
    {
        // maxLength is 1 because k >= 0,
        // a single element, subarray will always
        // have absolute difference zero
        int maxLength = 1;
 
        // Check for all possible subarrays
        for (int i = 0; i < arr.length; i++) {
            // Initalization of minimum &
            // maximum of current subarray
            int minOfSub = arr[i];
            int maxOfSub = arr[i];
 
            for (int j = i + 1; j < arr.length; j++) {
 
                // Update the values for minimum & maximum
                if (arr[j] > maxOfSub)
                    maxOfSub = arr[j];
 
                if (arr[j] < minOfSub)
                    minOfSub = arr[j];
 
                // Check if current subarray satisfies
                // the given condition
                if ((maxOfSub - minOfSub) <= k) {
                    int currLength = j - i + 1;
 
                    // Update the value for maxLength
                    if (maxLength < currLength)
                        maxLength = currLength;
                }
            }
        }
 
        // Return the final result
        return maxLength;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 6, 7 };
 
        int k = 2;
 
        int maxLength = computeLongestSubarray(arr, k);
        System.out.println(maxLength);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation to find the
# Longest subarray of the given array
# with absolute difference between
# elements less than or equal to integer K
def computeLongestSubarray (arr, k, n):
 
    # maxLength is 1 because k >= 0,
    # a single element, subarray will always
    # have absolute difference zero
    maxLength = 1
 
    # Check for all possible subarrays
    for i in range(n):
 
        # Initialization of minimum &
        # maximum of current subarray
        minOfSub = arr[i]
        maxOfSub = arr[i]
 
        for j in range(i + 1, n):
 
            # Update the values for
            # minimum & maximum
            if (arr[j] > maxOfSub):
                maxOfSub = arr[j]
 
            if (arr[j] < minOfSub):
                minOfSub = arr[j]
 
            # Check if current subarray
            # satisfies the given condition
            if ((maxOfSub - minOfSub) <= k):
                currLength = j - i + 1
 
                # Update the value for maxLength
                if (maxLength < currLength):
                    maxLength = currLength
 
    # Return the final result
    return maxLength
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 3, 6, 7 ]
    k = 2
    n = len(arr)
 
    maxLength = computeLongestSubarray(arr, k, n)
 
    print(maxLength)
 
# This code is contributed by himanshu77

chevron_right


Output: 

3

 

Time Complexity: O(n2)

Efficient Approach: 
To optimize the above approach the idea is to use Heap Data Structure. Initialize a minHeap that will store the indices of the current subarray such that the elements are in ascending order, where the smallest appears at the top and a maxHeap that will store the indices of the current subarray such that the elements are in descending order, where the largest element appears at the top. Then iterate over the entire array and for each iteration check if:

  • All the subarray elements satisfy the condition of maxOfSub-minOfSub <= k, then we compare maxLength so far to the length of current subarray and update maxLength to maximum of either maxLength or current subarray length.
  • If the condition is not satisfied then increase the beginning pointer for subarray by 1 and remove all indices from minHeap and maxHeap which are not included in the new subarray.
  • After each iteration we increase our subarray length by incrementing the end pointer.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find the Longest
// subarray of the given array with absolute
// difference between elements less than or equal
// to integer K using Heaps
import java.util.*;
 
class GFG {
    public static int computeLongestSubarray(int arr[],
                                                 int k)
    {
        // Stores the maximum length subarray so far
        int maxLength = 0;
 
        Deque<Integer> maxHeap = new LinkedList<>();
        Deque<Integer> minHeap = new LinkedList<>();
 
        // Marks to the beginning and end
        // pointer for current subarray
        int beg = 0, end = 0;
 
        while (end < arr.length) {
 
            // Stores the current element being
            // added to the subarray
            int currEl = arr[end];
 
            // Remove indices of all elements smaller
            // than or equal to current from maxHeap
            while (maxHeap.size() > 0 &&
                       arr[maxHeap.peekLast()] <= currEl)
                maxHeap.removeLast();
 
            // Add current element's index to maxHeap
            maxHeap.addLast(end);
 
            // Remove indices of all elements larger
            // than or equal to current from minHeap
            while (minHeap.size() > 0 &&
                       arr[minHeap.peekLast()] >= currEl)
                minHeap.removeLast();
 
            // Add current element's index to minHeap
            minHeap.addLast(end);
 
            // Index of maximum of current subarray
            int maxOfSub = arr[maxHeap.peekFirst()];
 
            // Index of minimum of current subarray
            int minOfSub = arr[minHeap.peekFirst()];
 
            // check if the largest possible difference
            // between a pair of elements <= k
            if (maxOfSub - minOfSub <= k) {
                // Length of current subarray
                int currLength = end - beg + 1;
 
                // Update maxLength
                if (maxLength < currLength)
                    maxLength = currLength;
            }
 
            else {
                // If current subarray doesn't satisy
                // the condition then remove the starting
                // element from subarray that satisy
                // increment the beginning pointer
                beg++;
 
                // Remove elements from heaps that
                // are not in the subarray anymore
                while (minHeap.size() > 0 &&
                               minHeap.peekFirst() < beg)
                    minHeap.removeFirst();
 
                while (maxHeap.size() > 0 &&
                               maxHeap.peekFirst() < beg)
                    maxHeap.removeFirst();
            }
 
            end++;
        }
 
        // Return the final answer
        return maxLength;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 6, 7 };
 
        int k = 2;
 
        int maxLength = computeLongestSubarray(arr, k);
        System.out.println(maxLength);
    }
}

chevron_right


Output: 

3

 

Time Complexity: O(n) because every element of the array is added and removed from the heaps only once.
 

competitive-programming-img




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : chitranayal, himanshu77