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
- 1 ≤ n ≤ 10⁴
Edge cases to test
- n a perfect square:
1 - n = 1
- n of the form 4ᵃ(8b + 7):
4
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
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Longest Palindromic Subsequence (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)