Minimum Shipping Capacity

35 min · shipWithinDays()

A ship that's too small misses the deadline; a ship that's too large wastes capacity. Your job is to find the exact boundary.

Packages wait in the order given by weights. Each day, load a contiguous group — adjacent packages from the front of those still waiting — without exceeding one fixed ship capacity. Return the smallest capacity that sends every package within days days.

A few ground rules:

  • Package order can't change, and no package can be split.
  • The ship uses the same capacity every day.
  • days is at most the number of packages, so the schedule always contains work.

Constraints

  • 1 <= weights.length <= 100_000
  • 1 <= days <= weights.length
  • 1 <= weights[i] <= 500

Hints

Test one capacity greedily

Walk through the packages in order. Keep loading the current day until the next package would exceed the capacity, then start a new day with that package.

Fence the answer

The capacity can't be below the heaviest package. The sum of every weight is always enough because it ships everything in one day.

Search the first success

If a capacity meets the deadline, every larger capacity does too. Binary search for the smallest capacity whose greedy schedule uses at most days days.

Follow-up

Why does filling each day as much as possible minimize the number of days for a fixed capacity?

Visible cases

Examples

Example 1

ready
Input
weights = [
  1,
  2,
  3,
  1,
  1
]
days = 4
Expected
3
Why
capacity 3 ships the ordered groups [1,2], [3], [1,1]

Example 2

ready
Input
weights = [
  3,
  2,
  2,
  4,
  1,
  4
]
days = 3
Expected
6
Why
capacity 6 is the first capacity that fits three days

Example 3

ready
Input
weights = [
  5,
  8,
  2
]
days = 1
Expected
15
Why
one day must carry the full total weight

Interview signal

Asked at

AmazonGoogleMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite