Find the most valued alphabet in the String | Java 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
class GFG { static int MAX = 26 ; static char maxAlpha ( String str , int len ) { int [ ] first = new int [ MAX ] ; int [ ] last = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { first [ i ] = - 1 ; last [ i ] = - 1 ; } for ( int i = 0 ; i < len ; i ++ ) { int index = ( str . charAt ( 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 ' ) ; } public static void main ( String [ ] args ) { String str = " abbba " ; int len = str . length ( ) ; System . out . print ( maxAlpha ( str , len ) ) ; } }