Skip to content

Commit 64d98b7

Browse files
authored
Create Minimum Number of Squares
1 parent 456a3c3 commit 64d98b7

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
Given an integer N, find and return the count of minimum numbers required to represent N as a sum of squares.
3+
That is, if N is 4, then we can represent it as : {1^2 + 1^2 + 1^2 + 1^2} and {2^2}.
4+
The output will be 1, as 1 is the minimum count of numbers required to represent N as sum of squares.
5+
6+
Input format :
7+
The first and the only line of input contains an integer value, 'N'.
8+
9+
Output format :
10+
Print the minimum count of numbers required.
11+
12+
Constraints :
13+
0 <= n <= 10 ^ 4
14+
Time Limit: 1 sec
15+
16+
Sample Input 1 :
17+
12
18+
Sample Output 1 :
19+
3
20+
Explanation of Sample Output 1 :
21+
12 can be represented as :
22+
A) (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1)
23+
24+
B) (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (1^1) + (2 ^ 2)
25+
26+
C) (1^1) + (1^1) + (1^1) + (1^1) + (2 ^ 2) + (2 ^ 2)
27+
28+
D) (2 ^ 2) + (2 ^ 2) + (2 ^ 2)
29+
30+
As we can see, the output should be 3.
31+
32+
Sample Input 2 :
33+
9
34+
Sample Output 2 :
35+
1
36+
*/
37+
public class Solution {
38+
39+
public static int minCount(int n) {
40+
//Your code goes here
41+
int dp[] = new int[n+1];
42+
for (int i=0;i<n+1;i++)
43+
dp[i]=-1;
44+
45+
return minCountHelper(n,dp);
46+
}
47+
48+
private static int minCountHelper(int n, int[] dp)
49+
{
50+
if (n==0)
51+
return 0;
52+
53+
int minVal = Integer.MAX_VALUE;
54+
for (int i=1;i*i<=n;i++)
55+
{
56+
if (dp[n-(i*i)]==-1)
57+
dp[n-(i*i)]=minCountHelper(n-(i*i),dp);
58+
int currVal = dp[n-(i*i)];
59+
if (currVal<minVal)
60+
minVal=currVal;
61+
}
62+
63+
return minVal+1;
64+
}
65+
66+
}

0 commit comments

Comments
 (0)