Maximum count of values of S modulo M lying in a range [ L , R ] after performing given operations on the array | Lookup table ; Function to count the value of S after adding arr [ i ] or arr [ i - 1 ] to the sum S at each time ; Base Case ; Store the mod value ; If the mod value lies in the range then return 1 ; Else return 0 ; Store the current state ; If already computed , return the computed value ; Recursively adding the elements to the sum adding ai value ; Adding arr [ i ] - 1 value ; Return the maximum count to check for root value as well ; Avoid counting idx = 0 as possible solution we are using idx != 0 ; Return the value of current state ; Driver Code
let dp = new Map ( ) ; function countMagicNumbers ( idx , sum , a , n , m , l , r ) { if ( idx == n ) { let temp = sum % m ; if ( temp == l || temp == r || ( temp > l && temp < r ) ) return dp [ [ idx , sum ] ] = 1 ; else return dp [ [ idx , sum ] ] = 0 ; } let curr = [ idx , sum ] ; if ( dp . has ( curr ) ) return dp [ curr ] ; let ls = countMagicNumbers ( idx + 1 , sum + a [ idx ] , a , n , m , l , r ) ; let rs = countMagicNumbers ( idx + 1 , sum + ( a [ idx ] - 1 ) , a , n , m , l , r ) ; let temp1 = Math . max ( ls , rs ) ; let temp = sum % m ; if ( ( temp == l || temp == r || ( temp > l && temp < r ) ) && idx != 0 ) { temp1 += 1 ; } dp [ [ idx , sum ] ] = temp1 ; return dp [ [ idx , sum ] ] ; } let N = 5 , M = 22 , L = 14 , R = 16 ; let arr = [ 17 , 11 , 10 , 8 , 15 ] ; document . write ( countMagicNumbers ( 0 , 0 , arr , N , M , L , R ) ) ;