Count of N | C # program to implement the above approach ; Function to return the count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ j ] stores the number of such i - digit numbers ending with j ; Stores the results of length i ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find actual count of i - digit numbers ending with j ; Update [ ] dp ; Stores the readonly answer ; Return the readonly answer ; Driver Code
using System ; class GFG { public static long getCount ( int n , int k ) { if ( n == 1 ) return 10 ; long [ ] dp = new long [ 11 ] ; long [ ] next = new long [ 11 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ i ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 9 ; j ++ ) { int l = Math . Max ( 0 , j - k ) ; int r = Math . Min ( 9 , j + k ) ; next [ l ] += dp [ j ] ; next [ r + 1 ] -= dp [ j ] ; } for ( int j = 1 ; j <= 9 ; j ++ ) next [ j ] += next [ j - 1 ] ; for ( int j = 0 ; j < 10 ; j ++ ) { dp [ j ] = next [ j ] ; next [ j ] = 0 ; } } long count = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) count += dp [ i ] ; return count ; } public static void Main ( String [ ] args ) { int n = 2 , k = 1 ; Console . WriteLine ( getCount ( n , k ) ) ; } }