![]() |
VOOZH | about |
Given an integer N. Then your task is to output a minimum number of operations to reduce N into 1. You can below operations to do the same:
Examples:
Input: N = 10
Output: 3
Explanation: The operations are performed as:
- First Operation: Subtract 1 form 10. Updated value of N = 9.
- Second Operation: N = 9 is divisible by 3. Update N as 9/3 = 3
- Second Operation: N = 3 is divisible by 3. Update N as 3/3 = 1
Now N is reduced into 1 by following sequence of N's value as {10 → 9 → 3 → 1}. Thus, minimum number of operations required are 3.
Input: 4
Output: 2
Explanation: 4 can be reduced into 1 with two ways {4 → 3 → 1} or {4 → 2 → 1}. Both requires minimum operations as 2.
Approach: Implement the idea below to solve the problem
In this problem we have 3 choices to perform operations, in solving choice-based problems we can use Dynamic Programming. For this problem we will take help of Dynamic Programming in the form of map and for each value of N, we can explore all the given conditions and can proceed further with minimum of them.
Steps were taken to solve the problem:
Below is the code to implement the above approach:
3
Time Complexity: O(Log N)
Auxiliary Space: O(Log N)