Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded.

Problem: A truck holds at most 8 boxes. Each box type is (count, units per box). Maximise the total units loaded.
def max_units(boxes, cap):
    total = 0
    for cnt, units in sorted(boxes, key=lambda b: -b[1]):
        take = min(cnt, cap)
        total += take * units; cap -= take
        if cap == 0: break
    return total
print(max_units([(2, 5), (4, 9), (3, 7), (5, 2)], 8))
What is printed?
  1. A. 57
  2. B. 76
  3. C. 60
  4. D. 62

Correct answer: D. 62

Every box occupies one slot, so take the boxes with most units first: 4 × 9 = 36, 3 × 7 = 21, then 1 of the 5-unit boxes = 5 → 62. Since all boxes have equal 'weight', this greedy is optimal (unlike general 0/1 knapsack). O(k log k) for k box types.

More Coding Interview Problems questions

Exams that ask this topic