Check if any valid sequence is divisible by M | Python3 program to check if any valid sequence is divisible by M ; 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
def isPossible ( n , index , Sum , M , arr , dp ) : NEW_LINE INDENT global MAX NEW_LINE if index == n : NEW_LINE INDENT if ( Sum % M ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if dp [ index ] [ Sum ] != - 1 : NEW_LINE INDENT return dp [ index ] [ Sum ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT placeAdd = isPossible ( n , index + 1 , Sum + arr [ index ] , M , arr , dp ) NEW_LINE DEDENT ' NEW_LINE INDENT placeMinus = isPossible ( n , index + 1 , Sum - arr [ index ] , M , arr , dp ) NEW_LINE res = placeAdd or placeMinus NEW_LINE dp [ index ] [ Sum ] = res NEW_LINE return res NEW_LINE DEDENT MAX = 1000 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE M = 4 NEW_LINE dp = [ [ - 1 ] * MAX for i in range ( n + 1 ) ] NEW_LINE res = isPossible ( n , 0 , 0 , M , arr , dp ) NEW_LINE if res : NEW_LINE INDENT print ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( False ) NEW_LINE DEDENT