text: Find the most valued alphabet in the String | C ++ implementation of the approach ; Function to return the maximum valued alphabet ; To store the first and the last occurrence of all the characters ; Set the first and the last occurrence of all the characters to - 1 ; Update the occurrences of the characters ; Only set the first occurrence if it hasn 't already been set ; To store the result ; For every alphabet ; If current alphabet doesn 't appear  in the given string ; If the current character has the highest value so far ; Driver code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; char maxAlpha ( string str , int len ) { int first [ MAX ] , last [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { first [ i ] = -1 ; last [ i ] = -1 ; } for ( int i = 0 ; i < len ; i ++ ) { int index = ( str [ i ] - ' a ' ) ; if ( first [ index ] == -1 ) first [ index ] = i ; last [ index ] = i ; } int ans = -1 , maxVal = -1 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( first [ i ] == -1 ) continue ; if ( ( last [ i ] - first [ i ] ) > maxVal ) { maxVal = last [ i ] - first [ i ] ; ans = i ; } } return ( char ) ( ans + ' a ' ) ; } int main ( ) { string str = " abbba " ; int len = str . length ( ) ; cout << maxAlpha ( str , len ) ; return 0 ; }