// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Lookup table
static Dictionary<Tuple<int, int>, int> dp = new Dictionary<Tuple<int, int>, int>();
// Function to count the value of S
// after adding arr[i] or arr[i - 1]
// to the sum S at each time
static int countMagicNumbers(int idx, int sum, int[] a, int n, int m, int l, int r)
{
// Base Case
if (idx == n) {
// Store the mod value
int Temp = sum % m;
// If the mod value lies in
// the range then return 1
if (Temp == l || Temp == r
|| (Temp > l && Temp < r))
return dp[new Tuple<int,int>(idx, sum)] = 1;
// Else return 0
else
return dp[new Tuple<int,int>(idx, sum)] = 0;
}
// Store the current state
Tuple<int,int> curr
= new Tuple<int,int>(idx, sum);
// If already computed, return the
// computed value
if (dp.ContainsKey(curr))
return dp[curr];
// Recursively adding the elements
// to the sum adding ai value
int ls = countMagicNumbers(idx + 1,
sum + a[idx],
a, n,
m, l, r);
// Adding arr[i] - 1 value
int rs = countMagicNumbers(idx + 1,
sum + (a[idx] - 1),
a, n, m, l, r);
// Return the maximum count to
// check for root value as well
int temp1 = Math.Max(ls, rs);
int temp = sum % m;
// Avoid counting idx = 0 as possible
// solution we are using idx != 0
if ((temp == l || temp == r
|| (temp > l && temp < r))
&& idx != 0) {
temp1 += 1;
}
// Return the value of current state
return dp[new Tuple<int,int>(idx, sum)] = temp1;
}
static void Main() {
int N = 5, M = 22, L = 14, R = 16;
int[] arr = { 17, 11, 10, 8, 15 };
Console.Write(countMagicNumbers(0, 0, arr, N, M, L, R));
}
}
// This code is contributed by divyeshrabadiya07.