ProgrammingVery hardCAT · MBA placement

Fractional knapsack with capacity 50. Items as (value, weight): (60,10), (100,20), (120,30). Items are sorted by value per unit weight, highest first, and the fraction of an item may be taken. What total value is printed (an integer)?

Fractional knapsack with capacity 50. Items as (value, weight): (60,10), (100,20), (120,30). Items are sorted by value per unit weight, highest first, and the fraction of an item may be taken. What total value is printed (an integer)?
cap = 50; total = 0
for each item (v, w) in ratio order
    if w <= cap then total += v; cap -= w
    else total += v * cap / w; cap = 0
end for
Print total
  1. A. 240
  2. B. 220
  3. C. 160
  4. D. 280

Correct answer: A. 240

Taking the fraction 20/30 of the 120 item adds 80, giving 240. Whole items only give 160, the 0/1 optimum 220 forbids fractions, and summing all values ignores the capacity of 50.

More Pseudocode and Code Tracing questions

Exams that ask this topic