Min Steps to One Using Dynamic Programming
Given a positive integer N
, your task is to determine the minimum number of steps required to reduce N
to 1.
Allowed Operations:
1) Subtract 1 from it: n = n - 1
2) If n is divisible by 2, divide it by 2: if n % 2 == 0, then n = n / 2
3) If n is divisible by 3, divide it by 3: if n % 3 == 0, then n = n / 3
Input:
The input starts with an integer 'T', the number of test cases.
Each of the next 'T' lines contains a single integer 'N'.
Output:
Return an integer for each test case which denotes the minimum steps needed to reduce the number to 1.
Example:
Input:
T = 1
N = 4
Output:
2
Explanation:
Starting from N = 4, divide by 2 to get 2, then subtract 1 to reach 1.
Constraints:
- 1 <= T <= 5
- 1 <= N <= 105
Time Limit: 1 second
Note:
This problem requires the implementation of the function that calculates the minimum steps, without printing the output.
AnswerBot
1y
The task is to find the minimum number of steps required to reduce a positive integer to 1 using three given operations.
Use dynamic programming to solve the problem efficiently.
Create an array to stor...read more
Help your peers!
Add answer anonymously...
Top MasterCard Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in MasterCard Software Developer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app