Algo-Sim › Dynamic Programming

Perfect Squares

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Fewest perfect squares that sum to n: Coin Change where the coins are 1, 4, 9, …, or a BFS whose levels count squares.

Problem

Given an integer n, return the smallest number of perfect squares (1, 4, 9, 16, …) that add up to n. A square may be used more than once.

Constraints

Edge cases to test

Follow-up questions

Is there a math shortcut?
Lagrange: every n is a sum of four squares, and Legendre says exactly those of the form 4ᵃ(8b + 7) need four. Checking 1 and 2 squares first gives O(√n).
Why BFS?
Levels count squares used, and the first level that reaches 0 is the answer: often faster than filling the whole table.

Solution

Java

public int numSquares(int n) {
    int[] dp = new int[n + 1];
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;
    for (int i = 1; i <= n; i++) {
        for (int s = 1; s * s <= i; s++) {
            dp[i] = Math.min(dp[i], dp[i - s * s] + 1);
        }
    }
    return dp[n];
}

Python

def num_squares(n):
    dp = [float("inf")] * (n + 1)
    dp[0] = 0
    for i in range(1, n + 1):
        s = 1
        while s * s <= i:
            dp[i] = min(dp[i], dp[i - s * s] + 1)
            s += 1
    return dp[n]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int numSquares(int n) {
        vector<int> dp(n + 1, INT_MAX);
        dp[0] = 0;
        for (int i = 1; i <= n; i++) {
            for (int s = 1; s * s <= i; s++) {
                dp[i] = min(dp[i], dp[i - s * s] + 1);
            }
        }
        return dp[n];
    }
};

More Dynamic Programming problems