I have a problem statement - given n, find the least number of perfect square numbers that sum to n.
Due to some reasons, I was trying out the least efficient brute force approach based on formula -
perfectSquaresRequired(n) = (perfectSquaresRequired(n-k) + 1) for all k which is perfect square<=n
I wrote a recursive function to implement it in java. Here numSquares is the function getting called and getSteps is the function that implements the recursion logic.
Set<Integer> squares;
public int numSquares(int n) {
squares = new HashSet();
for (int i=1; i*i<=n; i++)
squares.add(i*i);
return getSteps(n);
}
public int getSteps(int k) {
if (squares.contains(k))
return 1;
int min=Integer.MAX_VALUE, cur;
for (Integer square : squares) {
if (square>k)
break;
cur = getSteps(k-square) + 1;
min = Math.min(cur, min);
}
return min;
}
The problem is I am getting absurd values from this code. However if I use anything other than Integer.MAX_VALUE in statement int min = Integer.MAX_VALUE i.e. any value smaller than 2147483647 (even 2147483646), I am getting correct answer.
I have been learning DSA for only a month now. Can anyone explain why is this happening?
