Reduce array to a single element by repeatedly replacing adjacent unequal pairs with their maximum | C ++ program for the above approach ; Function to print the index from where the operation can be started ; Initialize B [ ] ; Initialize save ; Make B [ ] equals to arr [ ] ; Sort the array B [ ] ; Traverse from N - 1 to 1 ; If B [ i ] & B [ i - 1 ] are unequal ; If all elements are same ; If arr [ 1 ] is maximum element ; If arr [ N - 1 ] is maximum element ; Find the maximum element ; Driver Code ; Given array arr [ ] ; Length of array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printIndex ( int arr [ ] , int N ) { int B [ N ] ; int save = -1 ; for ( int i = 0 ; i < N ; i ++ ) { B [ i ] = arr [ i ] ; } sort ( B , B + N ) ; for ( int i = N - 1 ; i >= 1 ; i -- ) { if ( B [ i ] != B [ i - 1 ] ) { save = B [ i ] ; break ; } } if ( save == -1 ) { cout << -1 << endl ; return ; } if ( save == arr [ 0 ] && save != arr [ 1 ] ) { cout << 1 ; } else if ( save == arr [ N - 1 ] && save != arr [ N - 2 ] ) { cout << N ; } for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( save == arr [ i ] && ( save != arr [ i - 1 ] save != arr [ i + 1 ] ) ) { cout << i + 1 ; break ; } } } int main ( ) { int arr [ ] = { 5 , 3 , 4 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printIndex ( arr , N ) ; return 0 ; }