Skip to content

Commit 6ebd817

Browse files
dhananjay-ngDhananjay Nagargoje
authored and
Dhananjay Nagargoje
committed
1d dp, in steps to reduce to 1
1 parent 965fdbd commit 6ebd817

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package problems.onRecursionAndDp;
2+
import java.util.*;
3+
import java.lang.*;
4+
import java.io.*;
5+
public class DPMinStepsToReduceToOne {
6+
/**
7+
* One dimensional DP
8+
* Given a number n, count minimum steps to minimise it to 1 according to the following criteria:
9+
*
10+
* If n is divisible by 2 then we may reduce n to n/2.
11+
* If n is divisible by 3 then you may reduce n to n/3.
12+
* Decrement n by 1.
13+
*
14+
*
15+
* Input:
16+
*
17+
* The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N denoting the number n.
18+
*
19+
*
20+
*
21+
* Output:
22+
*
23+
* Output the minimum steps to minimise the number in a new line for each test case.
24+
*
25+
*
26+
* Constraints:
27+
*
28+
* 1<= T <=1000
29+
*
30+
* 1<= N <=10000
31+
*
32+
*
33+
* Example:
34+
*
35+
* Input:
36+
*
37+
* 2
38+
*
39+
* 10
40+
*
41+
* 6
42+
*
43+
* Output:
44+
*
45+
* 3
46+
*
47+
* 2
48+
* @param args
49+
* @throws IOException
50+
*/
51+
public static void main (String[] args) throws IOException
52+
{
53+
Scanner in = new Scanner(System.in);
54+
StringBuilder result = new StringBuilder();
55+
int t = in.nextInt();
56+
int[] nums = new int[t];
57+
int max = -1;
58+
for(int i=0;i<t;i++){
59+
nums[i] = in.nextInt();
60+
if(nums[i] > max ) max = nums[i];
61+
}
62+
63+
64+
int[] dp = new int[max+1];
65+
dp[1] = 0;
66+
if(max > 1)
67+
dp[2] = 1;
68+
if(max>2)
69+
dp[3] = 1;
70+
71+
for(int i = 4;i<=max;i++){
72+
int q1 = Integer.MAX_VALUE;
73+
int q2 = Integer.MAX_VALUE;
74+
int q3 = Integer.MAX_VALUE;
75+
if(i % 3 == 0) q1 = 1 + dp[i / 3];
76+
if(i % 2 == 0) q2 = 1 + dp[i / 2];
77+
q3 = 1 + dp[i - 1];
78+
79+
dp[i] = Math.min(q1, Math.min(q2, q3));
80+
}
81+
for( int i = 0; i < t - 1; i++) {
82+
result.append(dp[nums[i]]).append("\n");
83+
}
84+
result.append(dp[nums[t-1]]);
85+
System.out.print(result.toString());
86+
87+
}
88+
}

0 commit comments

Comments
 (0)