oneby7

1-D Dynamic Programming Take it or skip it

522. Perfect Squares

Medium

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

Output: 2

Explanation: 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

Output: 4

Explanation: 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

Output: 2

Explanation: 100000 = 99856 + 144, which is 316² + 12².

Check your understanding

Work out the answer for this input before you write any code.

n = 43

Constraints

  • 1 ≤ n ≤ 105

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.