Data Structures & AlgorithmsHardProduct Company SDE pattern

What is printed? (subset sum with a boolean DP table)

What is printed? (subset sum with a boolean DP table)
a = [3, 34, 4, 12, 5, 2]
def can(t):
    dp = [True] + [False] * t
    for x in a:
        for s in range(t, x - 1, -1): dp[s] = dp[s] or dp[s - x]
    return dp[t]
print(can(9), can(30), can(56))
  1. A. True True True
  2. B. True False False
  3. C. True False True
  4. D. False False True

Correct answer: C. True False True

9 = 4 + 5. 30 cannot be formed: 34 is too big and the other values sum to only 26. 56 = 34 + 12 + 5 + 3 + 2. Iterating s downwards uses each number at most once (0/1 choice). O(n·t) time, O(t) space.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic