Perfect Squares

Given an integer n, return the least number of perfect square numbers that sum to n. A perfect square is an integer that is the square of an integer, such as 1, 4, 9 and 16. 3 and 11 are not perfect squares.

30:00

Perfect Squares
medium
Free written solution
Topics
Companies

Given an integer n, return the least number of perfect square numbers that sum to n.

A perfect square is an integer that is the square of an integer, such as 1, 4, 9 and 16. 3 and 11 are not perfect squares.

Example 1:
Input: {"n":12}
Output: 3
Constraints:
  • 1≤n≤1041 \leq n \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":12}

dp[k] will be the fewest squares that sum to k. dp[0] = 0 (nothing to add), every other slot starts at infinity.

For each amount i, try removing one square j² and reuse the best answer for what is left: dp[i] = min over j of dp[i - j²] + 1.

dp[k] = fewest squares summing to k

filling

read

0

0

∞

1

∞

2

∞

3

∞

4

∞

5

∞

6

∞

7

∞

8

∞

9

∞

10

∞

11

∞

12

Variables
VariableValue
n12
dp[0]0
DepthFunction Call
Stack empty
0/16