Maximum distance between two elements whose absolute difference is K | Java 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
import java . io . * ; import java . util . * ; class GFG { static int maxDistance ( int [ ] arr , int K ) { Map < Integer , Integer > map = new HashMap < > ( ) ; int maxDist = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( ! map . containsKey ( arr [ i ] ) ) map . put ( arr [ i ] , i ) ; if ( map . containsKey ( arr [ i ] + K ) ) { maxDist = Math . max ( maxDist , i - map . get ( arr [ i ] + K ) ) ; } if ( map . containsKey ( arr [ i ] - K ) ) { maxDist = Math . max ( maxDist , i - map . get ( arr [ i ] - K ) ) ; } } if ( maxDist == 0 ) return - 1 ; else return maxDist ; } public static void main ( String args [ ] ) { int [ ] arr = { 11 , 2 , 3 , 8 , 5 , 2 } ; int K = 2 ; System . out . println ( maxDistance ( arr , K ) ) ; } }