coding_challengeshigh priority
Ship Packages in D Days — Binary Search on Answer
📋 The problem — read this first
A conveyor belt has packages that must ship within `days` days. The i-th
package weighs weights[i]. Each day you load the ship with packages IN THE
GIVEN ORDER without exceeding its capacity. Find the LEAST ship capacity so
that everything ships within `days` days. (LeetCode 1011)
Key idea: the answer is monotonic — if capacity C works, every capacity > C
also works — so binary-search the capacity and test feasibility (how many days
a given capacity needs).
Example:
Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
With capacity 15 the loads are [1,2,3,4,5] [6,7] [8] [9] [10] = 5 days.
Capacity 14 needs 6 days, so 15 is the minimum.💡 The solution — step through it
1 / 5
example.cpp
1// LeetCode 1011 — Capacity To Ship Packages Within D Days.2// Ship weights[] IN ORDER; minimize the daily ship capacity so all3// packages ship within 'days' days.4int shipWithinDays(std::vector<int>& w, int days) {5 int lo = *std::max_element(w.begin(), w.end()); // >= heaviest box6 int hi = std::accumulate(w.begin(), w.end(), 0); // all in one day7 8 auto daysNeeded = [&](int cap) { // feasibility check9 int d = 1, load = 0;10 for (int x : w) {11 if (load + x > cap) { ++d; load = 0; } // new day12 load += x;13 }14 return d;15 };16 17 while (lo < hi) { // find MIN feasible cap18 int mid = lo + (hi - lo) / 2;19 if (daysNeeded(mid) <= days) hi = mid; // feasible -> shrink20 else lo = mid + 1; // infeasible -> grow21 }22 return lo; // lo == hi == answer23}Spot the pattern — binary search on the ANSWER
You're asked to MINIMIZE the daily capacity. Given a candidate capacity you can CHECK in O(n) whether everything ships within D days, and that check is MONOTONIC: a bigger capacity never needs more days. Minimize + linear feasibility + monotonic ⇒ binary-search the answer, not the array.
Tap ▶ to play · tap the dots or Next → to stepPlays automatically · Space to play/pause · ← / → to step · controls are above the diagram