Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Filling the truck

You run a delivery truck. Each box type comes with a number of boxes and a number of units in each box. The truck can hold only so many boxes, and you want to carry the most units in total.

Since every box takes the same space, the ones packed with more units are always better to load first.

Density rule: a box with 10 units is always better than a box with 5.
Sort descending: put the box types with the most units per box first.
Truck holds 4 boxes · box types sorted by units per box, best first
units/boxboxestake
type A
3
1
1
type B
2
2
type C
1
3
space
3
units
3

Type A is worth 3 per box. Take all 1 of them.

Move 1 of 3

The greedy loading loop

At each step, look at the space left in the truck. If the best box type has 5 boxes and the truck has room for 3, take 3 and stop. If the truck has room for 8, take all 5 and carry on with the next type.

Stop as soon as the space reaches zero.

Take the smaller: of the space left and the boxes available.
Reduce the space: by what you took, until it reaches 0.
In code
boxes.sort(key=lambda x: x[1], reverse=True)
total = 0
for count, units in boxes:
    take = min(space, count)
    total += take * units
    space -= take
    if space == 0:
        break
return total