Skip to content

Commit 52ea603

Browse files
solves perfect squares in java
1 parent 7376ddd commit 52ea603

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

src/PerfectSquares.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// https://leetcode.com/problems/perfect-squares
2+
// T: O(N * k) k = size of perfect squares array which is constant
3+
// S: O(N + k)
4+
5+
public class PerfectSquares {
6+
private static final int[] PERFECT_SQUARES = {
7+
1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576,
8+
625, 676, 729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600, 1681, 1764, 1849,
9+
1936, 2025, 2116, 2209, 2304, 2401, 2500, 2601, 2704, 2809, 2916, 3025, 3136, 3249, 3364, 3481, 3600, 3721,
10+
3844, 3969, 4096, 4225, 4356, 4489, 4624, 4761, 4900, 5041, 5184, 5329, 5476, 5625, 5776, 5929, 6084, 6241,
11+
6400, 6561, 6724, 6889, 7056, 7225, 7396, 7569, 7744, 7921, 8100, 8281, 8464, 8649, 8836, 9025, 9216, 9409,
12+
9604, 9801, 10000, 10_201
13+
};
14+
15+
public int numSquares(int n) {
16+
final int[] dp = new int[n + 1];
17+
dp[0] = dp[1] = 1;
18+
for (int i = 2 ; i < dp.length ; i++) {
19+
dp[i] = numSquares(i, dp);
20+
}
21+
return dp[dp.length - 1];
22+
}
23+
24+
private int numSquares(int n, int[] dp) {
25+
int result = Integer.MAX_VALUE, square;
26+
for (int i = 0 ; PERFECT_SQUARES[i] <= n ; i++) {
27+
square = PERFECT_SQUARES[i];
28+
result = Math.min(result, dp[square] + dp[n - square]);
29+
}
30+
return result;
31+
}
32+
}

0 commit comments

Comments
 (0)