// C# program to count the numbers in the range [L, R]
// whose sum of even digits is greater than the sum of odd digits
// using memoization.
using System;
class GfG {
static int countNumbers(int index, int evenSum,
int oddSum, int tight, string s,
int[, , , ] memo) {
// Base case: If we've processed all digits
if (index == s.Length) {
// Return 1 if evenSum > oddSum, else return 0
return evenSum > oddSum ? 1 : 0;
}
// Return memoized result if already computed
if (memo[index, evenSum, oddSum, tight] != -1) {
return memo[index, evenSum, oddSum, tight];
}
// Set limit for current digit (either tight or 9)
int limit = tight == 1 ? s[index] - '0' : 9;
int ans = 0;
// Loop over possible digits (0 to limit)
for (int d = 0; d <= limit; d++) {
// Update tight condition
int currTight
= (d == s[index] - '0') ? tight : 0;
// Recursive call based on digit type (odd or
// even)
if (d % 2 != 0) {
ans += countNumbers(index + 1, evenSum,
oddSum + d, currTight,
s, memo);
}
else {
ans += countNumbers(index + 1, evenSum + d,
oddSum, currTight, s,
memo);
}
}
// Memoize and return result
memo[index, evenSum, oddSum, tight] = ans;
return ans;
}
static void Main(string[] args) {
int L = 2;
int R = 10;
// Convert L and R to strings for easy digit
// processing
string s1 = R.ToString();
string s2 = (L - 1).ToString();
// Initialize memo table with -1 (indicating
// uncomputed state)
int maxIndex = s1.Length;
int maxSum
= maxIndex
* 9;
// Create the 4D memo array
int[, , , ] memo
= new int[maxIndex, maxSum + 1, maxSum + 1, 2];
// Manually initialize all elements of the 4D array
// to -1
for (int i = 0; i < maxIndex; i++) {
for (int j = 0; j <= maxSum; j++) {
for (int k = 0; k <= maxSum; k++) {
for (int l = 0; l < 2; l++) {
memo[i, j, k, l] = -1;
}
}
}
}
// Count valid numbers in range [0, L-1]
int cnt1 = countNumbers(0, 0, 0, 1, s2, memo);
// Reset memo table for the next range
for (int i = 0; i < maxIndex; i++) {
for (int j = 0; j <= maxSum; j++) {
for (int k = 0; k <= maxSum; k++) {
for (int l = 0; l < 2; l++) {
memo[i, j, k, l] = -1;
}
}
}
}
int cnt2 = countNumbers(0, 0, 0, 1, s1, memo);
Console.WriteLine(cnt2 - cnt1);
}
}