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.
- Minimum number of operations required to reduce N to 0
- Minimum number of operations required to reduce N to 1
- Minimum number of given operations required to reduce the array to 0 element
- Reduce a number to 1 by performing given operations | Set 2
- Min number of operations to reduce N to 0 by subtracting any digits from N
- Count the number of operations required to reduce the given number
- Min operations to reduce N by multiplying by any number or taking square root
- Reduce the number to minimum multiple of 4 after removing the digits
- Min operations to reduce N to 1 by multiplying by A or dividing by B
- Find maximum operations to reduce N to 1
- Count operations of the given type required to reduce N to 0
- Minimum prime number operations to convert A to B
- Minimum number operations required to convert n to m | Set-2
- Convert a number m to n using minimum number of given operations
- Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M
- Minimum number of operations required to obtain a given Binary String
- Minimum number of increment/decrement operations such that array contains all elements from 1 to N
- Minimum number of operations on a binary string such that it gives 10^A as remainder when divided by 10^B
- Minimum number of steps required to obtain the given Array by the given operations
- Find minimum number of merge operations to make an array palindrome