Check if any valid sequence is divisible by M | Javascript implementation of above approach ; 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
const MAX = 100 ; function isPossible ( n , index , modulo , M , arr , dp ) { modulo = ( ( modulo % M ) + M ) % M ; if ( index == n ) { if ( modulo == 0 ) { return 1 ; } return 0 ; } if ( dp [ index ] [ modulo ] != - 1 ) { return dp [ index ] [ modulo ] ; } var placeAdd = isPossible ( n , index + 1 , modulo + arr [ index ] , M , arr , dp ) ; var placeMinus = isPossible ( n , index + 1 , modulo - arr [ index ] , M , arr , dp ) ; var res = placeAdd ; dp [ index ] [ modulo ] = res ; return res ; } var arr = [ 1 , 2 , 3 , 4 , 6 ] ; var n = arr . length ; var M = 4 ; var dp = Array ( n + 1 ) ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = Array ( MAX ) . fill ( - 1 ) ; } var res ; if ( isPossible ( n , 1 , arr [ 0 ] , M , arr , dp ) == 1 ) { res = true ; } else { res = false ; } document . write ( res ? " " : " " ) ;