Maximum distance between two unequal elements | Function to return the maximum distance between two unequal elements ; If first and last elements are unequal they are maximum distance apart ; Fix first element as one of the elements and start traversing from the right ; Break for the first unequal element ; To store the distance from the first element ; Fix last element as one of the elements and start traversing from the left ; Break for the first unequal element ; To store the distance from the last element ; Maximum possible distance ; Driver code
def maxDistance ( arr , n ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ n - 1 ] ) : NEW_LINE INDENT return ( n - 1 ) ; NEW_LINE DEDENT i = n - 1 ; NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ 0 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i -= 1 ; NEW_LINE DEDENT distFirst = - 1 if ( i == 0 ) else i ; NEW_LINE i = 0 ; NEW_LINE while ( i < n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ n - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT distLast = - 1 if ( i == n - 1 ) else ( n - 1 - i ) ; NEW_LINE maxDist = max ( distFirst , distLast ) ; NEW_LINE return maxDist ; NEW_LINE DEDENT arr = [ 4 , 4 , 1 , 2 , 1 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxDistance ( arr , n ) ) ; NEW_LINE