Math Fundamentals18 sections · 814 units
Open in Course

Perfect Squares - The Insight (DP with square roots)

Building from smaller values

Define dp[i]dp[i] as the minimum number of perfect squares that sum to ii. You want dp[n]dp[n].

For each ii, try subtracting all perfect squares j2ij^2 \leq i. Then dp[i]=1+min(dp[ij2])dp[i] = 1 + \min(dp[i - j^2]) for all valid jj. The base case is dp[0]=0dp[0] = 0.

How many perfect squares j2ij^2 \leq i are there? About i\sqrt{i}. So for each ii, you do O(i)O(\sqrt{i}) work. Total time: O(nn)O(n \sqrt{n}).