Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity.

Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity.
def frac(items, W):
    total = 0.0
    for v, w in sorted(items, key=lambda x: x[0] / x[1], reverse=True):
        take = min(w, W); total += v * take / w; W -= take
        if W == 0: break
    return f"{total:.2f}"
print(frac([(60, 10), (100, 20), (120, 30), (40, 5)], 45))
What is printed?
  1. A. 220.00
  2. B. 260.00
  3. C. 240.00
  4. D. 180.00

Correct answer: C. 240.00

Ratios: 8 (40/5), 6 (60/10), 5 (100/20), 4 (120/30). Take items 4, 1 and 2 fully (weight 35, value 200) and 10 of the last item's 30 kg (value 120 × 10/30 = 40): 240.00. Unlike 0/1 knapsack, the greedy ratio order is optimal when items can be split.

More Coding Interview Problems questions

Exams that ask this topic