Leftmost and rightmost indices of the maximum and the minimum element of an array | C ++ implementation of above idea ; Function to return the index of the rightmost minimum element from the array ; First element is the minimum in a sorted array ; While the elements are equal to the minimum update rightMin ; Final check whether there are any elements which are equal to the minimum ; Function to return the index of the leftmost maximum element from the array ; Last element is the maximum in a sorted array ; While the elements are equal to the maximum update leftMax ; Final check whether there are any elements which are equal to the maximum ; Driver code ; First element is the leftmost minimum in a sorted array ; Last element is the rightmost maximum in a sorted array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getRightMin ( int arr [ ] , int n ) { int min = arr [ 0 ] ; int rightMin = 0 ; int i = 1 ; while ( i < n ) { if ( arr [ i ] == min ) rightMin = i ; i *= 2 ; } i = rightMin + 1 ; while ( i < n && arr [ i ] == min ) { rightMin = i ; i ++ ; } return rightMin ; } int getLeftMax ( int arr [ ] , int n ) { int max = arr [ n - 1 ] ; int leftMax = n - 1 ; int i = n - 2 ; while ( i > 0 ) { if ( arr [ i ] == max ) leftMax = i ; i /= 2 ; } i = leftMax - 1 ; while ( i >= 0 && arr [ i ] == max ) { leftMax = i ; i -- ; } return leftMax ; } int main ( ) { int arr [ ] = { 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum ▁ left ▁ : ▁ " << 0 << " STRNEWLINE " ; cout << " Minimum ▁ right ▁ : ▁ " << getRightMin ( arr , n ) << " STRNEWLINE " ; cout << " Maximum ▁ left ▁ : ▁ " << getLeftMax ( arr , n ) << " STRNEWLINE " ; cout << " Maximum ▁ right ▁ : ▁ " << ( n - 1 ) ; }