Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA

What is the minimum number of perfect squares (1, 4, 9, 16, ...) whose sum is exactly 12? Run the DP over all squares not exceeding 12.

What is the minimum number of perfect squares (1, 4, 9, 16, ...) whose sum is exactly 12? Run the DP over all squares not exceeding 12.
n=12
sq=[i*i for i in range(1,n+1) if i*i<=n]
INF=10**9; dp=[0]+[INF]*n
for x in range(1,n+1):
    dp[x]=min(dp[x-s]+1 for s in sq if s<=x)
print(dp[n])
What is printed?
  1. A. 12
  2. B. 4
  3. C. 3
  4. D. -1

Correct answer: C. 3

Unbounded min-count DP over the squares is exact: 12 = 4+4+4 needs three squares, since 12 is not a sum of two squares. Greedy largest-square removal uses 9+1+1+1 and gives four, allowing only unit squares gives 12, and using each square at most once makes 12 unreachable.

More Coding Interview Problems questions

Exams that ask this topic