![]() |
VOOZH | about |
Given an integer array arr[] and an integer x, Find the longest sub-array where the absolute difference between any two elements is not greater than x.
Examples:
Input: arr[] = [8, 4, 5, 6, 7], x = 3
Output: [4, 5, 6, 7]
Explanation: The longest valid subarray is [4, 5, 6, 7] because max = 7, min = 4 β difference = 3 which is less than equal to x.Input: arr[] = [1, 10, 12, 13, 14], x = 2
Output: [12, 13, 14]
Explanation: The longest valid subarray is[12, 13, 14]because max = 14, min = 12 β difference = 2 which is less than equal to x.
Table of Content
The idea is to consider all subarrays one by one, find the maximum and minimum element of that sub-array and check if their difference is not greater than x. Among all such sub-arrays print the longest sub-array.
4 5 6 7
We use a sliding window with an ordered map to maintain the minimum and maximum values in the current subarray. The window expands until the absolute difference exceeds x; if it does, we shrink the window from the left until the condition is satisfied again.
Working:
In C# and JavaScript, a custom structure is needed for min/max since they donβt have a built-in ordered map.
4 5 6 7
We will be using two deques to maintain the minimum and maximum of the current window in O(1). Expand the window while the difference β€ x, and shrink it when the difference > x to find the longest valid subarray.
Working:
4 5 6 7