Leftmost and rightmost indices of the maximum and the minimum element of an array | Java implementation of the approach ; If found new minimum ; If arr [ i ] = min then rightmost index for min will change ; If found new maximum ; If arr [ i ] = max then rightmost index for max will change ; Driver code
public class GFG { public static void findIndices ( int arr [ ] , int n ) { int leftMin = 0 , rightMin = 0 ; int leftMax = 0 , rightMax = 0 ; int min = arr [ 0 ] , max = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( arr [ i ] < min ) { leftMin = rightMin = i ; min = arr [ i ] ; } else if ( arr [ i ] == min ) rightMin = i ; if ( arr [ i ] > max ) { leftMax = rightMax = i ; max = arr [ i ] ; } else if ( arr [ i ] == max ) rightMax = i ; } System . out . println ( " Minimum ▁ left ▁ : ▁ " + leftMin ) ; System . out . println ( " Minimum ▁ right ▁ : ▁ " + rightMin ) ; System . out . println ( " Maximum ▁ left ▁ : ▁ " + leftMax ) ; System . out . println ( " Maximum ▁ right ▁ : ▁ " + rightMax ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 } ; int n = arr . length ; findIndices ( arr , n ) ; } }