Maximum distance between two occurrences of same element in array | Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its index in map ; Else update max distance ; Driver Program
def maxDistance ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE maxDict = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT maxDict = max ( maxDict , i - mp [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT return maxDict NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print maxDistance ( arr , n ) NEW_LINE DEDENT