Check if any valid sequence is divisible by M | Java 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
import java . util . * ; class GFG { static final int MAX = 1000 ; static boolean isPossible ( int n , int index , int sum , int M , int arr [ ] , int 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 ; } boolean placeAdd = isPossible ( n , index + 1 , sum + arr [ index ] , M , arr , dp ) ; boolean placeMinus = isPossible ( n , index + 1 , sum - arr [ index ] , M , arr , dp ) ; boolean res = ( placeAdd placeMinus ) ; dp [ index ] [ sum ] = ( res ) ? 1 : 0 ; return res ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 6 } ; int n = arr . length ; int M = 4 ; int dp [ ] [ ] = new int [ n + 1 ] [ MAX ] ; for ( int i = 0 ; i < n + 1 ; i ++ ) Arrays . fill ( dp [ i ] , - 1 ) ; boolean res ; res = isPossible ( n , 0 , 0 , M , arr , dp ) ; System . out . println ( ( res ? " True " : " False " ) ) ; } }