Count of N | Java Program to implement the above approach ; Function to return count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ i ] [ j ] stores the number of such i - digit numbers ending in j ; 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 values of i - digit numbers ending in j ; Stores the final answer ; Driver Code
import java . util . * ; class GFG { public static long getCount ( int n , int k ) { if ( n == 1 ) return 10 ; long dp [ ] [ ] = new long [ n + 1 ] [ 11 ] ; for ( int i = 1 ; i <= 9 ; i ++ ) dp [ 1 ] [ 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 ) ; dp [ i ] [ l ] += dp [ i - 1 ] [ j ] ; dp [ i ] [ r + 1 ] -= dp [ i - 1 ] [ j ] ; } for ( int j = 1 ; j <= 9 ; j ++ ) dp [ i ] [ j ] += dp [ i ] [ j - 1 ] ; } long count = 0 ; for ( int i = 0 ; i <= 9 ; i ++ ) count += dp [ n ] [ i ] ; return count ; } public static void main ( String [ ] args ) { int n = 2 , k = 1 ; System . out . println ( getCount ( n , k ) ) ; } }