Skip to content
Advertisement

Explain the logic of ‘Count of N-digit numbers with absolute difference of adjacent digits not exceeding K’ in Detail

Can someone please help me understand the logic of following Dynamic Programmming question Found this one at geeksforgeeks.com. I am unable to understand even after going through the answer provided.

Question:

Count of N-digit numbers with absolute difference of adjacent digits not exceeding K | Set 2

Given two integers N and K, the task is to find the count of N-digit numbers such that the absolute difference of adjacent digits in the number is not greater than K.

Examples:

Input: N = 2, K = 1

Output: 26

Explanation: The numbers are 10, 11, 12, 21, 22, 23, 32, 33, 34, 43, 44, 45, 54, 55, 56, 65, 66, 67, 76, 77, 78, 87, 88, 89, 98, 99

Input: N = 3, K = 2

Output: 188

Python3 solution:

JavaScript

This code is contributed by Shivam Singh

Link: https://www.google.com/amp/s/www.geeksforgeeks.org/count-of-n-digit-numbers-with-absolute-difference-of-adjacent-digits-not-exceeding-k-set-2/amp/

I am unable to understand the logic in following lines

JavaScript

Advertisement

Answer

N=2 so we are dealing with strictly 2 digit numbers

K=1 so each digit in the current number shall be no more than 1 digit greater or less than its neighbors

While the answer is 26 (the count of such numbers), lets take a look at why the answer includes 10, 11, and 12 but not 13

10 is good as the absolute value of 10 (the digits of 10) is less than or equal to 1 (the value of K)

13 is bad as the absolute value of 13 is 2 and 2 is greater than K

Note that as N increases, the number of pairwise digit comparisons required will also increase.

I’ll skip parsing someone else’s code with meaningless variable names. Here is how I might attempt to solve this:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement