-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumCount.java
More file actions
60 lines (49 loc) · 1.4 KB
/
MinimumCount.java
File metadata and controls
60 lines (49 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Minimum Count
Send Feedback
Given an integer N, find and return the count of minimum numbers, sum of whose squares is equal to N.
That is, if N is 4, then we can represent it as : {1^2 + 1^2 + 1^2 + 1^2} and {2^2}. Output will be 1, as 1 is the minimum count of numbers required.
Note : x^y represents x raise to the power y.
Input Format :
Integer N
Output Format :
Required minimum count
Constraints :
1 <= N <= 1000
Sample Input 1 :
12
Sample Output 1 :
3
Sample Output 1 Explanation :
12 can be represented as :
1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1
1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 1^1 + 2^2
1^1 + 1^1 + 1^1 + 1^1 + 2^2 + 2^2
2^2 + 2^2 + 2^2
As we can see, the output should be 3.
Sample Input 2 :
9
Sample Output 2 :
1
public class Solution {
public static int minCount(int n) {
// count[i] - represents minimum count of squares for integer n
if(n <= 3) {
return n;
}
int count[] = new int[n + 1];
count[0] = 0;
count[1] = 1;
count[2] = 2;
count[3] = 3;
for(int i = 4; i <= n; i++) {
int ans = i;
for(int j = 1; j <= i/2; j++) {
int k = i - (j * j);
if(k >= 0)
ans = Math.min(ans, count[k] + 1);
}
count[i] = ans;
}
return count[n];
}
}