Perfect Squares
Find the fewest perfect squares that add up to a number, using the answers for every smaller number.
Given an integer nn
Example 1
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2
Output: 2
Explanation: 13 = 4 + 9.
The Idea
Imagine a shop whose coins are worth 1, 4, 9, 16 and so on, one coin for every perfect square. You have to pay 12, and you want to hand over as few coins as possible.
The natural plan is to take the biggest coin that fits, then repeat. For 12 that is 9, and the 3 left over can only be paid as 1 + 1 + 1, so four coins in all. Yet 4 + 4 + 4 pays 12 with three. Taking the biggest coin each time is called a greedy choice, and here it loses: the 9 leaves a remainder, 3, that costs three more coins.
So how do we know which squares to use, without trying every mix of them? Turn the question around and look at the last square in the sum. If the last one is 4, the rest adds up to 8, and paying 8 with the fewest squares is the same problem with a smaller number. The best answer for 12 is therefore one square plus the best answer for 12 - 1, 12 - 4 or 12 - 9, whichever is smallest.
That needs the answers for smaller numbers first, so we keep them in a table. Its entry for a number i is called dp[i]dp[0]
The row labelled number i runs from 0 to 12, and the row below it holds dp[i]dp[11]dp[3]
The orange arrow, last square 4, starts at dp[8]dp[12]dp[12]
Solution Approach
Trying every mix of squares works but repeats itself. The table avoids that once three things are settled: the order its entries are filled in, which squares each entry tries, and what it holds at the start.
Trying every mix of squares
Why not simply try every way to write n
Filling the table in order
In which order should the entries be filled? The entry dp[i]ndp[i]
Which squares to try
Which squares does dp[i]k * kk * kdp[4]dp[0]
Starting values
What does the table hold before an entry is worked out? The entry dp[0]Integer.MAX_VALUEint
Java Solution
The method numSquares
- First, create the table
withdp entries, one for each number from 0 ton + 1 . Fill it withn usingInteger.MAX_VALUE , and setArrays.fill to 0.dp[0] - Work out the entries with two loops, one inside the other. The outer loop moves
from 1 toi , the number whose entry is being worked out.n - For each
, the inner loop movesi up from 1 whilek is at mostk * k . For each squarei , the countk * k is one candidate, anddp[i - k * k] + 1 keeps the smaller of it and the currentMath.min .dp[i] - When the outer loop is done,
holds the fewest squares fordp[n] , and the method returns it.n
The main
import java.util.Arrays;
public class PerfectSquares {
public static int numSquares(int n) {
int[] dp = new int[n + 1]; // dp[i]: fewest perfect squares that add up to i
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0; // 0 needs no squares at all
for (int i = 1; i <= n; i++) {
for (int k = 1; k * k <= i; k++) {
dp[i] = Math.min(dp[i], dp[i - k * k] + 1); // k * k is the last square
}
}
return dp[n];
}
public static void main(String[] args) {
System.out.println("n = 12: " + numSquares(12));
System.out.println("n = 13: " + numSquares(13));
System.out.println("n = 1: " + numSquares(1));
System.out.println("n = 7: " + numSquares(7));
System.out.println("n = 43: " + numSquares(43));
System.out.println("n = 10000: " + numSquares(10000));
}
}
Running it prints:
n = 12: 3
n = 13: 2
n = 1: 1
n = 7: 4
n = 43: 3
n = 10000: 1
The answer 3 for n = 12n = 7
The line n = 43: 3k = 100dp[0]
The check k * k <= ik * k < idp[1]Integer.MAX_VALUEdp[2]numSquares(4)
Complexity
The work is one pass over the numbers 1 to n
- Time: O(n √n), because each of the n entries tries every square up to its own number, and there are at most √n of those.
- Space: O(n), because the table keeps one count for each number from 0 to n.
No entry ever goes above 4. Every whole number is a sum of at most four squares, a result known as Lagrange's four-square theorem, and 7 is the smallest number that needs all four. Further results from number theory tell which numbers need exactly four, and they lead to an O(√n) check, but the table needs none of that theory.
The same table, with any set of coin values in place of the squares, solves