Find two equal subsequences of maximum length with at least one different index | Java implementation of the approach ; Function to return the required length of the subsequences ; To store the result ; To store the last visited position of lowercase letters ; Initialisation of frequency array to - 1 to indicate no character has previously occured ; For every character of the String ; Get the index of the current character ; If the current character has appeared before in the String ; Update the result ; Update the last position of the current character ; Driver code
class GFG { static int MAX = 26 ; static int maxLength ( String str , int len ) { int res = 0 ; int lastPos [ ] = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { lastPos [ i ] = - 1 ; } for ( int i = 0 ; i < len ; i ++ ) { int C = str . charAt ( i ) - ' a ' ; if ( lastPos [ C ] != - 1 ) { res = Math . max ( len - ( i - lastPos [ C ] - 1 ) - 1 , res ) ; } lastPos [ C ] = i ; } return res ; } public static void main ( String args [ ] ) { String str = " geeksforgeeks " ; int len = str . length ( ) ; System . out . println ( maxLength ( str , len ) ) ; } }