30:00
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.
1≤n≤1041 \leq n \leq 10^41≤n≤104
Run code to see results.
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
1
2
3
4
5
6
7
8
9
10
11
12
Find the fewest perfect squares (1, 4, 9, 16, ...) that add up to n. It is a coin-change problem where the coins are the squares up to n.