Maximum distance between two elements whose absolute difference is K | 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 ; Given array arr [ ] ; Given difference K ; Function call
function maxDistance ( arr , K , N ) { var map = new Map ( ) ; var maxDist = 0 ; for ( var i = 0 ; i < N ; i ++ ) { if ( ! map . has ( arr [ i ] ) ) map . set ( arr [ i ] , i ) ; if ( map . has ( arr [ i ] + K ) ) { maxDist = Math . max ( maxDist , i - map . get ( arr [ i ] + K ) ) ; } if ( map . has ( arr [ i ] - K ) ) { maxDist = Math . max ( maxDist , i - map . get ( arr [ i ] - K ) ) ; } } if ( maxDist == 0 ) return - 1 ; else return maxDist ; } var arr = [ 11 , 2 , 3 , 8 , 5 , 2 ] ; var N = arr . length ; var K = 2 ; document . write ( maxDistance ( arr , K , N ) ) ;