human
Write me a code to maximum distance between two elements whose absolute difference is K and the other steps required given the following:
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"
How can the above be solved in Python?
assistant
#Here is code to maximum distance between two elements whose absolute difference is K and the other steps required.
 def maxDistance ( arr , K ) :
	map = { }
	maxDist = 0
	for i in range ( len ( arr ) ) :
		if not arr [ i ] in map :
			map [ arr [ i ] ] = i
		if arr [ i ] + K in map :
			maxDist = max ( maxDist , i - map [ arr [ i ] + K ] )
		if arr [ i ] - K in map :
			maxDist = max ( maxDist , i - map [ arr [ i ] - K ] )
	if maxDist == 0 :
		return - 1
	else :
		return maxDist
arr = [ 11 , 2 , 3 , 8 , 5 , 2 ]
K = 2
print ( maxDistance ( arr , K ) )