Given an array arr[] and a number K, the task to find the maximum distance between two elements whose absolute difference is K. If it is not possible to find any maximum distance then print “-1”.
Example:
Input: arr[] = {3, 5, 1, 4, 2, 2}
Output: 5
Explanation:
The max distance between the two elements (3, 2) at index 0 and 5 is 5.Input: arr[] = {11, 2, 3, 8, 5, 2}
Output: 3
Explanation:
The max distance between the two elements (3, 2) at index 2 and 5 is 3.
Naive Approach: The idea is to pick each element(say arr[i]) one by one, search for the previous element (arr[i] – K) and the next element (arr[i] + K). If any of the two-element exists then find the maximum distance between the current element with its next or previous element.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use hashmap. Below are the steps:
- Traverse the array and store the index of the first occurrence in a HashMap.
- Now, for each element in the array arr[], check if arr[i] + K and arr[i] – K is present in the hashmap or not.
- If present, then update the distance from both the elements with the arr[i] and check for the next element.
- Print the maximum distance obtained after the above steps.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function that find maximum distance // between two elements whose absolute // difference is K int maxDistance(int arr[], int K, int N) { // To store the first index map<int, int> Map; // Traverse elements and find // maximum distance between 2 // elements whose absolute // difference is K int maxDist = 0; for(int i = 0; i < N; i++) { // If this is first occurrence // of element then insert // its index in map if (Map.find(arr[i]) == Map.end()) Map[arr[i]] = i; // If next element present in // map then update max distance if (Map.find(arr[i] + K) != Map.end()) { maxDist = max(maxDist, i - Map[arr[i] + K]); } // If previous element present // in map then update max distance if (Map.find(arr[i] - K) != Map.end()) { maxDist = max(maxDist, i - Map[arr[i] - K]); } } // Return the answer if (maxDist == 0) return -1; else return maxDist; } // Driver code int main() { // Given array arr[] int arr[] = { 11, 2, 3, 8, 5, 2 }; int N = sizeof(arr) / sizeof(arr[0]); // Given difference K int K = 2; // Function call cout << maxDistance(arr, K, N); return 0; } // This code is contributed by divyeshrabadiya07 |
Java
// Java program for the above approach import java.io.*; import java.util.*; class GFG { // Function that find maximum distance // between two elements whose absolute // difference is K static int maxDistance(int[] arr, int K) { // To store the first index Map<Integer, Integer> map = new HashMap<>(); // Traverse elements and find // maximum distance between 2 // elements whose absolute // difference is K int maxDist = 0; for (int i = 0; i < arr.length; i++) { // If this is first occurrence // of element then insert // its index in map if (!map.containsKey(arr[i])) map.put(arr[i], i); // If next element present in // map then update max distance if (map.containsKey(arr[i] + K)) { maxDist = Math.max( maxDist, i - map.get(arr[i] + K)); } // If previous element present // in map then update max distance if (map.containsKey(arr[i] - K)) { maxDist = Math.max(maxDist, i - map.get(arr[i] - K)); } } // Return the answer if (maxDist == 0) return -1; else return maxDist; } // Driver Code public static void main(String args[]) { // Given array arr[] int[] arr = { 11, 2, 3, 8, 5, 2 }; // Given difference K int K = 2; // Function call System.out.println( maxDistance(arr, K)); } } |
Python3
# Python3 program for the above approach # Function that find maximum distance # between two elements whose absolute # difference is K def maxDistance(arr, K): # To store the first index map = {} # Traverse elements and find # maximum distance between 2 # elements whose absolute # difference is K maxDist = 0 for i in range(len(arr)): # If this is first occurrence # of element then insert # its index in map if not arr[i] in map: map[arr[i]] = i # If next element present in # map then update max distance if arr[i] + K in map: maxDist = max(maxDist, i - map[arr[i] + K]) # If previous element present # in map then update max distance if arr[i] - K in map: maxDist = max(maxDist, i - map[arr[i] - K]) # Return the answer if maxDist == 0: return -1 else: return maxDist # Driver code # Given array arr[] arr = [ 11, 2, 3, 8, 5, 2 ] # Given difference K K = 2 # Function call print(maxDistance(arr,K)) # This code is contributed by Stuti Pathak |
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function that find maximum distance // between two elements whose absolute // difference is K static int maxDistance(int[] arr, int K) { // To store the first index Dictionary<int, int> map = new Dictionary<int, int>(); // Traverse elements and find // maximum distance between 2 // elements whose absolute // difference is K int maxDist = 0; for (int i = 0; i < arr.Length; i++) { // If this is first occurrence // of element then insert // its index in map if (!map.ContainsKey(arr[i])) map.Add(arr[i], i); // If next element present in // map then update max distance if (map.ContainsKey(arr[i] + K)) { maxDist = Math.Max(maxDist, i - map[arr[i] + K]); } // If previous element present // in map then update max distance if (map.ContainsKey(arr[i] - K)) { maxDist = Math.Max(maxDist, i - map[arr[i] - K]); } } // Return the answer if (maxDist == 0) return -1; else return maxDist; } // Driver Code public static void Main(String []args) { // Given array []arr int[] arr = { 11, 2, 3, 8, 5, 2 }; // Given difference K int K = 2; // Function call Console.WriteLine( maxDistance(arr, K)); } } // This code is contributed by Princi Singh |
2
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Count maximum elements of an array whose absolute difference does not exceed K
- Find K elements whose absolute difference with median of array is maximum
- Count of elements whose absolute difference with the sum of all the other elements is greater than k
- Maximum absolute difference between sum of two contiguous sub-arrays
- Maximum absolute difference between any two level sum in a N-ary Tree
- Maximum absolute difference between distinct elements in an Array
- Maximum distance between two unequal elements
- Distance of chord from center when distance between center and another equal length chord is given
- Pair with min absolute difference and whose product is N+1 or N+2
- Count pairs in an array whose absolute difference is divisible by K
- Nth positive number whose absolute difference of adjacent digits is at most 1
- Find maximum number of elements such that their absolute difference is less than or equal to 1
- Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum
- Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum
- Minimize the maximum absolute difference of adjacent elements in a circular array
- Last element remaining by deleting two largest elements and replacing by their absolute difference if they are unequal
- k-th smallest absolute difference of two elements in an array
- Maximum sum possible for a sub-sequence such that no two elements appear at a distance < K in the array
- Maximum absolute difference between sum of subarrays of size K
- Maximum time such that absolute difference between hour and minute lies in given range
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.

