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?- A. 12
- B. 4
- C. 3
- 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
- Count the subsequences (by position, not distinct strings) of "abcabc" that equal "abc". Run the DP that counts matches. python…
- Array a = [2, 3, 1, 1, 4, 2, 0, 3, 1, 1]; from index i you may jump to any index in [i+1, i+a[i]]. Find the minimum number of jumps from…
- Trapping rain water: heights h = [4, 2, 0, 3, 2, 5, 1, 0, 2]. Compute the total water trapped between the bars. python…
- The permutation p = [4, 3, 1, 7, 6, 2, 5] of 1..7 must be sorted by swaps of any two elements. What is the minimum number of swaps?…
- Count the lattice paths of length 8 with steps +1 and −1 that start at 0, never go below 0, and end at 0. Run the DP over positions and…
- How many ways are there to tile a 3 × 8 board completely with 1 × 2 dominoes (placed horizontally or vertically)? Count by DFS over the…