Search the answers
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?
We do not search a list here: we search the answers. The capacity is at least 8, the heaviest box, and at most 28, all boxes in one day. So lo = 8, hi = 28: 21 whole-number candidates.
One check
Binary search tests the middle candidate: mid = (8 + 28) // 2 = 18. Python's // divides and rounds down. The rings over the day plinths rise to 18 kg: that is the truck capacity we will try.
fits() loads boxes in order and starts a new day when the next box would pass the ring. Day 1: 4, 8, 3 (15 kg). Day 2: 5, 6, 2 (13 kg). 2 days: 18 fits.
A bigger truck never needs more days. So once 18 fits, every capacity above it fits too: the answers run no, no, ..., yes, yes. We want the first yes, so hi = 18 and 19 to 28 are dropped.
Halving the window
mid = (8 + 18) // 2 = 13. Day 1 takes 4 and 8 (12); day 2 takes 3 and 5 (8); 6 and 2 spill into day 3. Too many days, so every smaller capacity fails too: lo = 14.
mid = (14 + 18) // 2 = 16. Same split as for 18: 15 kg, then 13 kg. Two days, so it fits: hi = 16. The window is now 14 to 16, three candidates.
mid = (14 + 16) // 2 = 15. Day 1 holds 15 kg, exactly full; day 2 holds 13. Still two days: hi = 15.
mid = 14. Day 1: 12 kg. Day 2: 3, 5, 6 (14). The 2 needs day 3, so lo = 15. Now lo = hi = 15 and the loop stops: the smallest capacity is 15 kg.
5 checks found 15 among 21 candidates; counting up from 8 takes 8. Each check halves the window and reads all n boxes once, so the cost is O(n log R) for R candidates. It works because the answers never flip back to no.
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.