Related Articles
Maximum distance between two elements whose absolute difference is K
• Difficulty Level : Medium
• Last Updated : 15 Sep, 2020

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:

1. Traverse the array and store the index of the first occurrence in a HashMap.
2. Now, for each element in the array arr[], check if arr[i] + K and arr[i] – K is present in the hashmap or not.
3. If present, then update the distance from both the elements with the arr[i] and check for the next element.
4. 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 ``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 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`
Output:
```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.

My Personal Notes arrow_drop_up