Leftmost and rightmost indices of the maximum and the minimum element of an array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } cout << " Minimum ▁ left ▁ : ▁ " << leftMin << " STRNEWLINE " ; cout << " Minimum ▁ right ▁ : ▁ " << rightMin << " STRNEWLINE " ; cout << " Maximum ▁ left ▁ : ▁ " << leftMax << " STRNEWLINE " ; cout << " Maximum ▁ right ▁ : ▁ " << rightMax << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 2 , 1 , 1 , 2 , 1 , 5 , 6 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findIndices ( arr , n ) ; }