Leftmost and rightmost indices of the maximum and the minimum element of an array | Javascript 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
function findIndices ( arr , n ) { let leftMin = 0 , rightMin = 0 ; let leftMax = 0 , rightMax = 0 ; let min = arr [ 0 ] , max = arr [ 0 ] ; for ( let 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 ; } document . write ( " " + leftMin + " " ) ; document . write ( " " + rightMin + " " ) ; document . write ( " " + leftMax + " " ) ; document . write ( " " + rightMax + " " ) ; } let arr = [ 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 ] ; let n = arr . length ; findIndices ( arr , n ) ;