ProgrammingHardTCS CodeVita · Infosys HackWithInfy

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]
print(knap([(2, 3), (3, 4), (4, 5)], 5), knap([(1, 1)], 0))
  1. A. 8 0
  2. B. 7 0
  3. C. 7 1
  4. D. 5 0

Correct answer: B. 7 0

The inner loop runs downward so each item is used at most once. With capacity 5, the best choice is items of weight 2 and 3, with value 7. A capacity of 0 can take nothing.

More Python Programming questions

Exams that ask this topic