Given an integer N, the task is to reduce N to 1 with the following two operations:
- 1 can be subtracted from each of the digits of the number only if the digit is greater than 0 and the resultant number doesn’t have any leading 0s.
- 1 can be subtracted from the number itself.
The task is to find the minimum number of such operations required to reduce N to 1.
Input: N = 35
35 -> 24 -> 14 -> 13 -> 12 -> 11 -> 10 -> … -> 1 (14 operations)
Input: N = 240
Approach: It can be observed that if the number is power of 10 i.e. N = 10p then the number of operations will be (10 * p) – 1. For example, if N = 102 then operations will be (10 * 2) – 2 = 19
i.e. 100 -> 99 -> 88 -> 77 -> … -> 33 -> 22 -> 11 -> 10 -> 9 -> 8 -> … -> 2 -> 1.
Now, the task is to first convert the given to a power of 10 with the given operations and then count the number of operations required to reduce that power of 10 to 1. The sum of these operations is the required answer. The number of operations required to convert a number to a power of will be max(first_digit – 1, second_digit, third_digit, …, last_digit), this is because every digit can be reduced to 0 but the first digit must be 1 in order for it to be power of 10 with equal number of digits.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.