Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 456a3c3

Browse files
Create Min steps to 1 using DP
1 parent b077c42 commit 456a3c3

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
Given a positive integer 'n', find and return the minimum number of steps that 'n' has to take to get reduced to 1. You can perform any one of the following 3 steps:
3+
1.) Subtract 1 from it. (n = n - ­1) ,
4+
2.) If n is divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) ,
5+
3.) If n is divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ).
6+
7+
Input format :
8+
The first and the only line of input contains an integer value, 'n'.
9+
10+
Output format :
11+
Print the minimum number of steps.
12+
13+
Constraints :
14+
1 <= n <= 10 ^ 6
15+
Time Limit: 1 sec
16+
17+
Sample Input 1 :
18+
4
19+
Sample Output 1 :
20+
2
21+
Explanation of Sample Output 1 :
22+
For n = 4
23+
Step 1 : n = 4 / 2 = 2
24+
Step 2 : n = 2 / 2 = 1
25+
26+
Sample Input 2 :
27+
7
28+
Sample Output 2 :
29+
3
30+
Explanation of Sample Output 2 :
31+
For n = 7
32+
Step 1 : n = 7 ­- 1 = 6
33+
Step 2 : n = 6 / 3 = 2
34+
Step 3 : n = 2 / 2 = 1
35+
*/
36+
public class Solution {
37+
38+
public static int countMinStepsToOne(int n) {
39+
//Your code goes here
40+
if (n==0 || n==1)
41+
return 0;
42+
else if (n==2 || n==3)
43+
return 1;
44+
45+
int[] dp = new int[n+1];
46+
for (int i=0;i<n+1;i++)
47+
dp[i]=-1;
48+
49+
//Setting base cases
50+
dp[1]=0;
51+
dp[2]=1;
52+
dp[3]=1;
53+
for (int i=4;i<=n;i++)
54+
{
55+
//System.out.println("Current i: "+i);
56+
int ans1=dp[i-1];
57+
int ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE;
58+
if (i%2==0)
59+
{
60+
ans2=dp[i/2];
61+
}
62+
if (i%3==0)
63+
{
64+
ans3=dp[i/3];
65+
}
66+
//System.out.println("ans1: "+ans1+", ans2: "+ans2+", ans3: "+ans3);
67+
dp[i]=Math.min(ans1,Math.min(ans2,ans3))+1;
68+
//System.out.println(i+": "+dp[i]);
69+
}
70+
return dp[n];
71+
}
72+
73+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /