SDE & MLE Prep

279. Perfect Squares

Problem

Return the fewest perfect squares (1, 4, 9, 16, …) that add up to n.

Example: 12 → 3 (4 + 4 + 4); 13 → 2 (4 + 9)

Constraints: n ≤ 10⁴.

Coin change where coins are the squares ≤ n: dp[i] = 1 + min(dp[i − k²]).

Complexity: O(n√n).

class Solution:
    def numSquares(self, n: int) -> int:
        squares = [k * k for k in range(1, int(n ** 0.5) + 1)]
        dp = [0] + [n] * n
        for i in range(1, n + 1):
            for sq in squares:
                if sq > i:
                    break
                dp[i] = min(dp[i], dp[i - sq] + 1)
        return dp[n]