![]() |
VOOZH | about |
You are given an integer N. On each step, you may subtract one of the digits from the number. How many steps are required to make the number equal to 0?
Examples:
Input: N = 27
Output: 5
Explanation: 27 can be reduced to 0 in 5 steps:
- Step 1: 27 - 7 = 20
- Step 2: 20 - 2 = 18
- Step 3: 18 - 8 = 10
- Step 4: 10 - 1 = 9
- Step 5: 9 - 9 = 0
Input: N = 17
Output: 3
Explanation: 17 can be reduced to 0 in 3 steps:
- Step 1: 17 - 7 = 10
- Step 2: 10 - 1 = 9
- Step 3: 9 - 9 = 0
Approach: To solve the problem, follow the below idea:
The problem can be solved using Dynamic Programming. Maintain a dp[] array such that dp[i] stores the minimum number of steps to make i equal to 0. We can iterate i from 1 to N, and for each i, and minimize dp[i] using all the digits of i.
Let's say we have already calculated minimum number of steps for all numbers from 1 to (i - 1), and now we need to calculate minimum steps for number i. To calculate minimum number of steps for number i, we will find all the digits of i and for every digit d, dp[i] = min(dp[i], 1 + dp[i - d]). After all the iterations, dp[N] will store the final answer.
Step-by-step algorithm:
Below is the implementation of the algorithm:
3
Time Complexity: O(N * logN), where N is the number which we need to reduce.
Auxiliary Space: O(N)