Longest sub | Python3 implementation of the 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
import numpy as np NEW_LINE import sys NEW_LINE N = 100 NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE dp = np . zeros ( ( N , 3 ) ) ; NEW_LINE v = np . zeros ( ( N , 3 ) ) ; NEW_LINE def findLargestString ( s , i , r ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return INT_MIN ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] ; NEW_LINE DEDENT v [ i ] [ r ] = 1 ; NEW_LINE dp [ i ] [ r ] = max ( 1 + findLargestString ( s , i + 1 , ( r * 2 + ( ord ( s [ i ] ) - ord ( '0' ) ) ) % 3 ) , findLargestString ( s , i + 1 , r ) ) ; NEW_LINE return dp [ i ] [ r ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "101" ; NEW_LINE print ( findLargestString ( s , 0 , 0 ) ) ; NEW_LINE DEDENT