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
def maxDistance ( arr , K ) : NEW_LINE INDENT map = { } NEW_LINE maxDist = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if not arr [ i ] in map : NEW_LINE INDENT map [ arr [ i ] ] = i NEW_LINE DEDENT if arr [ i ] + K in map : NEW_LINE INDENT maxDist = max ( maxDist , i - map [ arr [ i ] + K ] ) NEW_LINE DEDENT if arr [ i ] - K in map : NEW_LINE INDENT maxDist = max ( maxDist , i - map [ arr [ i ] - K ] ) NEW_LINE DEDENT DEDENT if maxDist == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return maxDist NEW_LINE DEDENT DEDENT arr = [ 11 , 2 , 3 , 8 , 5 , 2 ] NEW_LINE K = 2 NEW_LINE print ( maxDistance ( arr , K ) ) NEW_LINE