Check if any valid sequence is divisible by M | javascript 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
var MAX = 1000 ; function isPossible ( n , index , sum , M , arr , dp ) { if ( index == n ) { if ( ( sum % M ) == 0 ) return true ; return false ; } else if ( sum < 0 sum >= MAX ) return false ; if ( dp [ index ] [ sum ] != - 1 ) { if ( dp [ index ] [ sum ] == 0 ) return false ; return true ; } var placeAdd = isPossible ( n , index + 1 , sum + arr [ index ] , M , arr , dp ) ; var placeMinus = isPossible ( n , index + 1 , sum - arr [ index ] , M , arr , dp ) ; var res = ( placeAdd placeMinus ) ; dp [ index ] [ sum ] = ( res ) ? 1 : 0 ; return res ; } var arr = [ 1 , 2 , 3 , 4 , 6 ] ; var n = arr . length ; var M = 4 ; var dp = Array ( n + 1 ) . fill ( - 1 ) . map ( x => Array ( MAX ) . fill ( - 1 ) ) ; res = isPossible ( n , 0 , 0 , M , arr , dp ) ; document . write ( ( res ? " " : " " ) ) ;