1-D Dynamic Programming Take it or skip it
522. Perfect Squares
Given an integer n, return the smallest number of perfect squares that add up to exactly n.
A perfect square is a whole number times itself, such as 1, 4, 9 or 16. You may use the same square as
many times as you like, and n on its own counts when it is a square.
Example 1
Input: n = 18
2Explanation: 18 = 9 + 9, and 18 is not a square itself, so two is the fewest. The sum 16 + 1 + 1 also makes 18, but it uses three squares.
Example 2
Input: n = 7
4Explanation: Only 1 and 4 fit under 7. The best sum is 4 + 1 + 1 + 1, since no two or three of them add up to 7.
Example 3
Input: n = 100000
2Explanation: 100000 = 99856 + 144, which is 316² + 12².
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ n ≤ 105
Clarifying questions
What you would ask an interviewer before writing any code.