Count of N | Function to find maximum between two numbers ; Function to find minimum between two numbers ; 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 final answer ; Return the final answer ; Driver Code
function max ( num1 , num2 ) { return ( num1 > num2 ) ? num1 : num2 ; } function min ( num1 , num2 ) { return ( num1 > num2 ) ? num2 : num1 ; } function getCount ( n , k ) { if ( n == 1 ) return 10 ; var dp = Array ( 11 ) . fill ( 0 ) ; var next = Array ( 11 ) . fill ( 0 ) ; for ( var i = 1 ; i <= 9 ; i ++ ) dp [ i ] = 1 ; for ( var i = 2 ; i <= n ; i ++ ) { for ( var j = 0 ; j <= 9 ; j ++ ) { var l = Math . max ( 0 , ( j - k ) ) ; var r = Math . min ( 9 , ( j + k ) ) ; next [ l ] += dp [ j ] ; next [ r + 1 ] -= dp [ j ] ; } for ( var j = 1 ; j <= 9 ; j ++ ) next [ j ] += next [ j - 1 ] ; for ( var j = 0 ; j < 10 ; j ++ ) { dp [ j ] = next [ j ] ; next [ j ] = 0 ; } } var count = 0 ; for ( var i = 0 ; i <= 9 ; i ++ ) count += dp [ i ] ; return count ; } var n = 2 , k = 1 ; document . write ( getCount ( n , k ) ) ;