AlgoFrames

Perfect squares

Standard · Write code · about 12 min

Return the fewest perfect squares (1, 4, 9, 16, …) that add up to n. A square may be used more than once.

Example 1

Input:

[12]

Output:

3

4 + 4 + 4.

Example 2

Input:

[13]

Output:

2

4 + 9.

Constraints

  • 1 ≤ n ≤ 10,000

Learn the idea first: Coin change: minimum coins and number of ways, a visual lesson.

More Coin change: minimum coins and number of ways problems