Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: What is the minimum number of perfect squares (1, 4, 9, ...) that sum to 12? Run the DP.

Problem: What is the minimum number of perfect squares (1, 4, 9, ...) that sum to 12? Run the DP.
INF = 10 ** 9
dp = [0] + [INF] * 12
for v in range(1, 13):
    for s in range(1, 5):
        if s * s <= v:
            dp[v] = min(dp[v], dp[v - s * s] + 1)
print(dp[12])
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 1

Correct answer: B. 3

12 = 4 + 4 + 4 with three squares, and 12 is not a sum of two squares, so 3 is minimal.

More Coding Interview Problems questions

Exams that ask this topic