day 1day 2day 389101112131415161718192021222324252627281lo, hi = max(ws), sum(ws)2while lo < hi:3 mid = (lo + hi) // 24 if fits(ws, mid, d):5 hi = mid6 else:7 lo = mid + 1lomidhi483562lohi
Boxes: as tall as they are heavy, shipped in orderRings: the capacity under test; the ruler: every candidate answerRed: too small (no) · green: big enough (yes)Six boxes (4, 8, 3, 5, 6, 2 kg) must ship in order within 2 days; the ruler holds every candidate truck capacity from 8 to 28. Each test lifts the rings to the middle candidate and loads the boxes day by day: a third day means the capacity is too small. Because the answers run no, then yes, each test throws away half the ruler: 5 tests find 15.

Search the answers

  1. Six boxes weigh 4, 8, 3, 5, 6, 2 kg. They must ship in this order, over at most 2 days. Each day one truck takes boxes until the next would pass its capacity. What is the smallest capacity that works?

One check

Halving the window

What happens

;; step 1/10 · problem
ws = [4, 8, 3, 5, 6, 2]   (kg, in shipping order)
d = 2   (days allowed)
one truckload per day; boxes stay in order
question: the smallest capacity cap with every box shipped in d days

The trick needs a monotone test: if fits(c) is True then fits(c + 1) is True. Here that holds because a bigger truck can carry every load a smaller one could, so the greedy never needs more days. Without that property binary search can skip past the answer. Each check at least halves the window of candidates, so 21 candidates need at most ⌈log2 21⌉ = 5 checks. With capacities up to a billion it would be about 30.