Video in progress
What is "binary search on the answer"? Explain it with the problem of the minimum ship capacity to deliver packages in D days.
We do binary search over the range of possible answers: the check "can we make it in D days with capacity C?" is monotonic, because increasing C never makes the answer worse. Each check is O(n), so the total is O(n log(sum)).
📖 Answer
The array doesn't have to be sorted. There is just one condition: the function feasible(x) must be monotonic, false up to some point and true from then on. We want the first true.
static int shipWithinDays(int[] weights, int days) {
int lo = Arrays.stream(weights).max().getAsInt(); // must be able to carry the heaviest package
int hi = Arrays.stream(weights).sum(); // everything in one day
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (canShip(weights, days, mid)) hi = mid; // mid is enough — try a smaller one
else lo = mid + 1;
}
return lo;
}
static boolean canShip(int[] w, int days, int cap) {
int used = 1, load = 0;
for (int x : w) {
if (load + x > cap) { used++; load = 0; }
load += x;
}
return used <= days;
}
Choosing the bounds correctly is half the work. If you start lo at 1, then when a single package is larger than the capacity, canShip doesn't count infinite days, so it can wrongly return true.
lo + (hi - lo) / 2 protects against overflow; (lo + hi) / 2 goes negative on large numbers.
Problems solved with this template: Koko eating bananas, splitting an array into M parts to minimize the largest sum, and maximizing the minimum distance between two points. The tell: when the problem asks for a "minimum of the maximum" or a "maximum of the minimum", first think about binary search on the answer.
Sign up to mark studied questions and save your progress.