Data Structures & AlgorithmsHardProduct Company SDE · greedy OA

Problem: Trucks carry boxes: each truck type is (count, units per box), and at most 10 boxes fit on the truck. Maximise units per truck with these types: [(1, 3), (2, 2), (3, 1)]. Use greedy by units per box and print the best total.

Problem: Trucks carry boxes: each truck type is (count, units per box), and at most 10 boxes fit on the truck. Maximise units per truck with these types: [(1, 3), (2, 2), (3, 1)]. Use greedy by units per box and print the best total.
types = [(1, 3), (2, 2), (3, 1)]
limit = 10
types.sort(key=lambda t: -t[1])
best = 0
for cnt, units in types:
    take = min(cnt, limit)
    best += take * units
    limit -= take
print(best)
What is printed?
  1. A. 6
  2. B. 30
  3. C. 3
  4. D. 10

Correct answer: D. 10

Greedy takes the 3-unit box, both 2-unit boxes and all three 1-unit boxes (6 boxes, within the limit of 10): 3 + 4 + 3 = 10. Taking only one box per type gives 6, ignoring the count and filling all 10 slots with 3-unit boxes gives 30, and writing best = instead of best += keeps only the last type (3).

More Coding Interview Problems questions

Exams that ask this topic