Capacity To Ship Packages Within D Days

Find the smallest ship that carries a line of packages, in order, within a given number of days.

Packages wait in a line on a conveyor belt, and all of them must be shipped within days days. Package i weighs weights[i]. Each day the ship takes packages from the front of the line, in order, and the weight it carries that day must not go over its capacity. Return the smallest capacity that ships every package within days days.

Example 1
Input: weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5
Output: 15
Explanation: [1, 2, 3, 4, 5], [6, 7], [8], [9], [10].
Example 2
Input: weights = [3, 2, 2, 4, 1, 4], days = 3
Output: 6
Explanation: [3, 2], [2, 4], [1, 4].
Example 3
Input: weights = [1, 2, 3, 1, 1], days = 4
Output: 3
Explanation: [1, 2], [3], [1, 1] takes 3 days, within the 4 allowed. Capacity 2 cannot carry the 3.
Solution

The Idea

Think of a delivery van that leaves once a day. It takes the next packages in line until one more would be too heavy, and that package waits for tomorrow. A bigger van clears the line in fewer days, a smaller one takes longer. How small can the van be and still finish on time?

Take Example 1, with packages weighing 1 to 10 and 5 days. Try a capacity of 15. Day 1 takes 1, 2, 3, 4 and 5, exactly 15. The 6 would not fit, so day 2 takes 6 and 7, which make 13. Adding 8 would make 21, so 8, 9 and 10 each go on a day of their own. That is 5 days, so 15 works.

Now try 14. Day 1 takes 1, 2, 3 and 4, which make 10, because adding 5 would make 15. Day 2 takes 5 and 6, and then 7, 8, 9 and 10 each need a day. That is 6 days, one too many.

So checking one capacity is a single walk along the line. But which capacities should we check? No capacity below 10 can carry the package that weighs 10, so 10 is the first one worth trying. Look at the picture below. It shows the capacities 10 to 20, the days each one needs, and whether that is within 5 days.

Capacities 10 to 20 for packages weighing 1 to 10, with the days each one needs: 7, 6, 6, 6, 6, then 5, 5, 4, 4, 4, 4. Capacities 10 to 14 are too small for 5 days; from 15 on every capacity is enough. The first yes is 15.

The row labelled days needed only goes down as the capacity grows. The row labelled within 5 days? reads no five times, then yes from 15 on, and it never flips back. That makes sense: a bigger ship can carry at least what a smaller one carried each day, so it never needs more days.

So the answer is the first yes in a row of no's followed by yes's. We do not have to check the capacities one by one to find it. Check the capacity in the middle instead: a yes means the first yes is there or to its left, and a no means it is to the right. Each check rules out half of the capacities left. This is binary search, used here on the possible answers rather than on an array, which is often called binary search on the answer.

Solution Approach

Turning that idea into code means settling three things: how to count the days one capacity needs, which capacities to search, and how to narrow the range with each check.

Counting the days for one capacity

How many days does a given capacity need? Load packages in order, and start a new day when the next package would push the load over the capacity. Taking as much as fits right now is called a greedy choice, and here it is the best one. Leaving a package for tomorrow when it fits today only puts more weight on the days that follow.

The range of capacities

Which capacities can be the answer? The smallest is the heaviest package, because the ship must carry it on some day. The largest is the total weight of all the packages, which ships everything on day 1 and so always works. For Example 1 the range is 10 to 55.

The simple way checks every capacity from the heaviest package upward until one works. Each check walks the whole line, so with many packages and a large total weight, that means a great many walks. Binary search needs only a few: 5 checks for Example 1.

Narrowing the range

How does one check narrow the range? Keep two numbers, lo and hi, with the answer always between them, and try the capacity mid halfway between. If mid is enough, the answer is mid or smaller, so hi becomes mid. It does not become mid - 1, because mid itself may be the answer. If mid is too small, so is every capacity below it, and lo becomes mid + 1. When lo and hi meet, they are on the answer.

Here is the search for Example 1, starting from lo = 10 and hi = 55:

lohimidDays neededDecision
1055322enough: hi = 32
1032213enough: hi = 21
1021155enough: hi = 15
1015126too small: lo = 13
1315146too small: lo = 15

After the last row, lo and hi are both 15, the first yes in the picture.

Java Solution

The method shipWithinDays works in these steps:

  1. First, set the range with one loop over the weights: lo becomes the heaviest package and hi the total weight.
  2. While lo is below hi, take mid, the middle of the range rounded down, written as lo + (hi - lo) / 2.
  3. Count the days mid needs with the helper daysNeeded. It starts the day counter count at 1 and the day's weight load at 0. For each weight w, if load + w is more than the capacity, a new day starts: count goes up by 1 and load goes back to 0. Then it adds w to load.
  4. If the count it returns is at most the allowed days, set hi to mid. Otherwise set lo to mid + 1.
  5. When the loop ends, lo equals hi, and lo is returned.

The main method runs the three examples, then a single day, one day per package, and two packages where one is much heavier than the other.

Java
public class CapacityToShipPackages {

    public static int shipWithinDays(int[] weights, int days) {
        int lo = 0;                     // smallest candidate: the heaviest package
        int hi = 0;                     // largest candidate: all packages in one day
        for (int w : weights) {
            lo = Math.max(lo, w);
            hi += w;
        }
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (daysNeeded(weights, mid) <= days) {
                hi = mid;               // mid is enough; the answer is mid or smaller
            } else {
                lo = mid + 1;           // mid is too small; so is everything below it
            }
        }
        return lo;
    }

    // Load packages in order; start a new day when the next one does not fit
    private static int daysNeeded(int[] weights, int capacity) {
        int count = 1;
        int load = 0;
        for (int w : weights) {
            if (load + w > capacity) {
                count++;
                load = 0;
            }
            load += w;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(shipWithinDays(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 5));
        System.out.println(shipWithinDays(new int[] {3, 2, 2, 4, 1, 4}, 3));
        System.out.println(shipWithinDays(new int[] {1, 2, 3, 1, 1}, 4));
        System.out.println(shipWithinDays(new int[] {1, 2, 3}, 1));      // one day: total
        System.out.println(shipWithinDays(new int[] {1, 2, 3}, 3));      // a day each: heaviest
        System.out.println(shipWithinDays(new int[] {1, 10}, 2));        // one heavy package
    }
}

Running it prints:

Output
15
6
3
6
3
10

Look at the first line: 15 is the first yes from the picture. The next two lines, 6 and 3, are the answers to Examples 2 and 3. With a single day for [1, 2, 3], everything goes at once, so the fourth line is the total weight, 6. With a day for each of those packages, the ship only has to carry the heaviest one, and the fifth line is 3.

The last line, 10, depends on lo starting at the heaviest package. daysNeeded never checks that a single package fits the ship. For capacity 1 and [1, 10], it puts 1 on day 1 and 10 on day 2, and counts 2 days. So a version that starts lo at 1 returns 1 for this input, a ship that cannot carry the second package.

The original implementation, CapacityToShipPackagesWithinDays.java, is on GitHub.

Complexity

The work is one walk along the packages for every capacity the binary search tries.

  • Time: O(n log S), where n is the number of packages and S their total weight. The range from the heaviest package to S holds at most S capacities, and each check halves it, so there are about log S checks. Each check runs daysNeeded over all n packages.
  • Space: O(1). The search keeps only lo, hi and mid, and daysNeeded keeps a day count and a load. The weights are read where they are, never copied or sorted.

Allocate Books follows the same plan, with students in place of days and pages in place of weights.