An interactive visualization of how binary search finds the minimum ship capacity. Watch the algorithm partition packages into daily shipments step by step.
Binary Search LeetCode 1011 ↗ Mediumdays days.i-th package on the conveyor belt has a weight of weights[i].
Each day, we load the ship with packages in the order given by the conveyor belt (we cannot skip or reorder packages).
We must not load more weight than the maximum capacity of the ship.days days.
fun shipWithinDays(weights: IntArray, days: Int): Int { var lo = weights.max() var hi = weights.sum() while (lo < hi) { val mid = (lo + hi) / 2 var ships = 1 var current = 0 for (w in weights) { if (current + w > mid) { ships++ current = 0 } current += w } if (ships <= days) // can ship → try smaller hi = mid else // too many ships → need more lo = mid + 1 } return lo // minimum valid capacity}
The ship capacity has a monotonic property: if we can ship all packages within days days
using capacity c, we can also do it with any capacity greater than c. This makes it a perfect
candidate for binary search on the answer.
lo = max(weights) (must be able to carry the heaviest single package), hi = sum(weights) (ship everything in one day)mid = (lo + hi) // 2mid, start a new ship (new day).hi = midlo = mid + 1
We do log(sum(weights) - max(weights)) binary search iterations, and each iteration scans all
n packages to simulate the greedy loading.