A perfect square is a whole number multiplied by itself: 1, 4, 9, 16, 25 and so on. Given a positive integer n, return the smallest number of perfect squares that add up to exactly n. The same square may be used as many times as you like.
Example 1
Input: n = 18
Output: 2
9 + 9 = 18. Starting with the biggest square that fits does worse here: 16 + 1 + 1 needs three.
Example 2
Input: n = 7
Output: 4
4 + 1 + 1 + 1 = 7. No two or three squares add up to 7.
Example 3
Input: n = 49
Output: 1
49 is itself a perfect square (7 × 7).
Constraints
1 <= n <= 10⁴Starting with the largest square that fits can go wrong: 12 is 4 + 4 + 4, but taking 9 first leaves 3, which needs three 1s. Think instead about the last square you add: whatever it is, what comes before it is the same question for a smaller number.
The first idea most people try is greedy: take the biggest square that fits, subtract it, repeat. It is wrong. Example 1 shows it: for 18, greedy takes 16 and is left with 2, which costs two more 1s, while 9 + 9 does it in two. For 43 it is worse: greedy builds 36 + 4 + 1 + 1 + 1, five squares, against 25 + 9 + 9, three.
Time O(√n)Space O(1)
The full walkthrough and code are part of Premium
18
2