Check if any valid sequence is divisible by M | Python3 Program to Check if any valid sequence is divisible by M ; Calculate modulo for this call ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing '+ ; 2. Try placing '- ; calculate value of res for recursive case ; store the value for res for current states and return for parent call ; Driver code ; MAX is the Maximum value M can take
MAX = 100 NEW_LINE def isPossible ( n , index , modulo , M , arr , dp ) : NEW_LINE INDENT modulo = ( ( modulo % M ) + M ) % M NEW_LINE if ( index == n ) : NEW_LINE INDENT if ( modulo == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ modulo ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ modulo ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT placeAdd = isPossible ( n , index + 1 , modulo + arr [ index ] , M , arr , dp ) NEW_LINE DEDENT ' NEW_LINE INDENT placeMinus = isPossible ( n , index + 1 , modulo - arr [ index ] , M , arr , dp ) NEW_LINE res = bool ( placeAdd or placeMinus ) NEW_LINE dp [ index ] [ modulo ] = res NEW_LINE return res NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE M = 4 NEW_LINE dp = [ [ - 1 ] * ( n + 1 ) ] * MAX NEW_LINE res = isPossible ( n , 1 , arr [ 0 ] , M , arr , dp ) NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT