Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (greedy fractional knapsack)

What is printed? (greedy fractional knapsack)
items = [(10, 60), (20, 100), (30, 120)]   # (weight, value)
cap, total = 50, 0.0
for w, v in sorted(items, key=lambda x: x[1] / x[0], reverse=True):
    take = min(w, cap); total += v * take / w; cap -= take
    if cap == 0: break
print(total)
  1. A. 240.0
  2. B. 220.0
  3. C. 160.0
  4. D. 180.0

Correct answer: A. 240.0

Taking items by value per kg (6, 5, 4) and splitting the last one: 60 + 100 + (20/30)·120 = 240. Greedy is optimal when fractions are allowed; for 0/1 items the best is only 220. O(n log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic