Command Palette
Search for a command to run...
Problem 30.7 · Knapsack DPMedium
What it teaches: Coin change where the coins are 1, 4, 9, 16, …
Practise it on judges as “Perfect Squares”.
The problem
Return the least number of perfect squares that sum to n.
Example 1
Input: n = 12
Output: 3
4 + 4 + 4.
Example 2
Input: n = 13
Output: 2
4 + 9.
Constraints
Pattern clues in the wording
- → Fewest items to reach a sum
These clues point to Knapsack DP: For each item, decide take or skip under a capacity; dp[c] is the best result using capacity c.
Stuck? Take one hint at a time
Solution.java · starterclass Solution {
public int numSquares(int n) {
return 0;
}
}
Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.
Test cases
| # | Input | Expected |
|---|
| 1 | n = 12 | 3 |
| 2 | n = 13 | 2 |
| 3 | n = 1 | 1 |
+ 1 hidden test the code runner will check