Maximum distance between two elements whose absolute difference is K | C ++ program for the above approach ; Function that find maximum distance between two elements whose absolute difference is K ; To store the first index ; Traverse elements and find maximum distance between 2 elements whose absolute difference is K ; If this is first occurrence of element then insert its index in map ; If next element present in map then update max distance ; If previous element present in map then update max distance ; Return the answer ; Driver code ; Given array arr [ ] ; Given difference K ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDistance ( int arr [ ] , int K , int N ) { map < int , int > Map ; int maxDist = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( Map . find ( arr [ i ] ) == Map . end ( ) ) Map [ arr [ i ] ] = i ; if ( Map . find ( arr [ i ] + K ) != Map . end ( ) ) { maxDist = max ( maxDist , i - Map [ arr [ i ] + K ] ) ; } if ( Map . find ( arr [ i ] - K ) != Map . end ( ) ) { maxDist = max ( maxDist , i - Map [ arr [ i ] - K ] ) ; } } if ( maxDist == 0 ) return -1 ; else return maxDist ; } int main ( ) { int arr [ ] = { 11 , 2 , 3 , 8 , 5 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 2 ; cout << maxDistance ( arr , K , N ) ; return 0 ; }