Longest sub | Java implementation of th approach ; Function to return the length of the largest sub - string divisible by 3 ; Base - case ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code
class GFG { final static int N = 100 ; final static int INT_MIN = Integer . MIN_VALUE ; static int dp [ ] [ ] = new int [ N ] [ 3 ] ; static int v [ ] [ ] = new int [ N ] [ 3 ] ; static int findLargestString ( String s , int i , int r ) { if ( i == s . length ( ) ) { if ( r == 0 ) return 0 ; else return INT_MIN ; } if ( v [ i ] [ r ] == 1 ) return dp [ i ] [ r ] ; v [ i ] [ r ] = 1 ; dp [ i ] [ r ] = Math . max ( 1 + findLargestString ( s , i + 1 , ( r * 2 + ( s . charAt ( i ) - '0' ) ) % 3 ) , findLargestString ( s , i + 1 , r ) ) ; return dp [ i ] [ r ] ; } public static void main ( String [ ] args ) { String s = "101" ; System . out . print ( findLargestString ( s , 0 , 0 ) ) ; } }