ProgrammingVery hardCAT · MBA placement

What is printed?

What is printed?
def knap(items, cap):
    dp = [0] * (cap + 1)
    for w, v in items:
        for c in range(cap, w - 1, -1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[cap]
def knap_wrong(items, cap):
    dp = [0] * (cap + 1)
    for w, v in items:
        for c in range(w, cap + 1):
            dp[c] = max(dp[c], dp[c - w] + v)
    return dp[cap]
items = [(2, 3), (3, 4), (4, 5)]
print(knap(items, 6), knap_wrong(items, 6))
  1. A. 7 9
  2. B. 8 8
  3. C. 9 9
  4. D. 8 9

Correct answer: D. 8 9

The 0/1 version iterates capacity downward so each item is used at most once, giving 8 for capacity 6. The wrong version iterates upward, so an item can be reused, giving 2 + 2 + 2 = 9.

More Python Programming questions

Exams that ask this topic