ProgrammingHardCAT · MBA placement

A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy below takes boxes with the most units per box first, as many as fit. What is the total number of units loaded (printed)?

A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy below takes boxes with the most units per box first, as many as fit. What is the total number of units loaded (printed)?
sort types by units descending; slots = 10; total = 0
for each (u, c) in order
    take t = min(c, slots) boxes; total = total + t * u; slots = slots - t
end for
Print total
  1. A. 45
  2. B. 26
  3. C. 37
  4. D. 34

Correct answer: C. 37

Taking the 5-unit boxes fills 3 slots (15 units), the 4-unit boxes fill 2 (8 units), the 3-unit boxes fill 4 (12 units), and one 2-unit box fills the last slot, for 37. Ignoring the slot count gives 45, sorting ascending gives 26, and multiplying by the box count gives 34.

More Pseudocode and Code Tracing questions

Exams that ask this topic