Skip to content
DSA Patterns
Menu
Language
Binary Search on AnswerLC #10114 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Capacity To Ship Packages Within D Days

Problem (restated)

Packages must ship in order within days days. Find the least weight capacity of the ship that makes this possible.

Intuition

Feasibility is monotonic in capacity: if C works, C+1 works. Binary search the capacity.

Approaches

Binary search on capacity

Unverified
Time O(n log S)Space O(1)

Idea. lo = max(weights), hi = sum(weights). For mid capacity, greedy-count days needed.

Walkthrough. weights=[1,2,3,4,5,6,7,8,9,10], days=5 → answer 15.

Trade-offs. Same pattern as Koko; define a clear canShip(cap) predicate.

Solution
export function shipWithinDays(weights: number[], days: number): number {
  let lo = Math.max(...weights);
  let hi = weights.reduce((a, b) => a + b, 0);
  const ok = (cap: number) => {
    let d = 1, load = 0;
    for (const w of weights) {
      if (load + w > cap) { d++; load = 0; }
      load += w;
    }
    return d <= days;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (ok(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}
export function shipWithinDays(weights: number[], days: number): number {
  let lo = Math.max(...weights);
  let hi = weights.reduce((a, b) => a + b, 0);
  const ok = (cap: number) => {
    let d = 1, load = 0;
    for (const w of weights) {
      if (load + w > cap) { d++; load = 0; }
      load += w;
    }
    return d <= days;
  };
  while (lo < hi) {
    const mid = lo + ((hi - lo) >> 1);
    if (ok(mid)) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Template connection

Search the ship capacity. The check packs left to right and counts the days that capacity needs. More than days means the ship is too small. Capacity must be at least the heaviest package.

Reflection

  • Same skeleton as Koko: binary-search the capacity, and feasible counts days without reordering the packages.
  • lo is max(weights), so one package fits. hi is the sum of the weights.
  • The package order is fixed. Reordering is not legal.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Ship packages in order within 5 days. Least capacity that fits.

1
0
2
1
3
2
4
3
5
4
6
5
7
6
8
7
9
8
10
9

lo = 10, hi = 55

Key:CurrentActive rangeMatchSettled