Maximum distance between two unequal elements | Java implementation of the approach ; 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
import java . io . * ; class GFG { static int maxDistance ( int arr [ ] , int n ) { if ( arr [ 0 ] != arr [ n - 1 ] ) return ( n - 1 ) ; int i = n - 1 ; while ( i > 0 ) { if ( arr [ i ] != arr [ 0 ] ) break ; i -- ; } int distFirst = ( i == 0 ) ? - 1 : i ; i = 0 ; while ( i < n - 1 ) { if ( arr [ i ] != arr [ n - 1 ] ) break ; i ++ ; } int distLast = ( i == n - 1 ) ? - 1 : ( n - 1 - i ) ; int maxDist = Math . max ( distFirst , distLast ) ; return maxDist ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 4 , 1 , 2 , 1 , 4 } ; int n = arr . length ; System . out . print ( maxDistance ( arr , n ) ) ; } }