DSA Factory
Free Binary search lessonsBinary search · Stage 2 · Search on the answer · Step 2

The smallest truck that will do

Find the smallest capacity that ships all the packages in order within a number of days. About 15 minutes.

The range of answers

Packages must be shipped in the order given, and each day the ship carries a run of packages whose total weight is within its capacity. What is the smallest capacity that gets everything shipped within a number of days?

The capacity can't be below the heaviest package, or that package never fits. And it never needs to be above the total weight, which ships everything in one day. So the answer lies somewhere in that range, and a bigger capacity can only help.

Lowest: the heaviest single package.
Highest: the total of all weights.
In code
low = max(weights)
high = sum(weights)
Weights 1 to 10, 5 days. Each column is one round of halving the capacity range.
12345
low
10
high
55
middle
32
days
2

The capacity is at least 10 and at most 55. Try the middle, 32: it ships in 2 days, within 5. It works, so look lower.

Move 1 of 5

The greedy check

To check a capacity, simulate. Start day one with an empty ship. Put the next package on if it fits, otherwise start a new day. Count the days used. If that is within the limit, the capacity works.

Fill each day as much as possible. Leaving room unused can never reduce the number of days needed, so this is the best plan for that capacity.

Fits: add it to today's load.
Doesn't fit: start a new day with it.
In code
def days_needed(capacity):
    days, load = 1, 0
    for w in weights:
        if load + w > capacity:
            days += 1
            load = 0
        load += w
    return days
Quick check

A capacity of 14 needs 6 days, but only 5 are allowed. What do you do next?

  1. ALook at larger capacities
  2. BLook at smaller capacities
  3. CStop and return 14
Show the answer

Look at larger capacities. A larger capacity can only need the same or fewer days.

Your problem

Smallest ship capacity

weights[i] is the weight of package i. The packages must be shipped in the order given, so each day the ship carries a run of consecutive packages whose total weight is at most the ship's capacity. Return the smallest capacity that ships all the packages within days days.

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

1 ≤ packages ≤ 50,000 · 1 ≤ weight ≤ 500 · 1 ≤ days ≤ packages

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve