Capacity to Ship Packages in D Days

Medium Binary Search

Problem

A conveyor belt has packages that must be shipped within days days. The i-th package has weight weights[i]. Each day you load the ship with packages in the order given by weights (you may not reorder them). The total weight loaded on any single day cannot exceed the ship's capacity. Return the least weight capacity that lets you ship every package within days days.

Example 1 Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5 Output: 15 Explain: A capacity of 15 works: day 1 ships [1,2,3,4,5] (sum 15), day 2 [6,7] (13), day 3 [8] (8), day 4 [9] (9), day 5 [10] (10). Capacity 14 is not enough because then we'd need more than 5 days.
Example 2 Input: weights = [3,2,2,4,1,4], days = 3 Output: 6 Explain: Capacity 6: day 1 [3,2] (5), day 2 [2,4] (6), day 3 [1,4] (5).
Example 3 Input: weights = [1,2,3,1,1], days = 4 Output: 3 Explain: Capacity 3: day 1 [1,2], day 2 [3], day 3 [1,1], day 4 nothing — fits in 4 days.

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def shipWithinDays(self, weights, days):
        def need(cap):
            d, cur = 1, 0
            for w in weights:
                if cur + w > cap:
                    d += 1
                    cur = 0
                cur += w
            return d
        lo, hi = max(weights), sum(weights)
        while lo < hi:
            mid = (lo + hi) // 2
            if need(mid) <= days:
                hi = mid
            else:
                lo = mid + 1
        return lo

Java

class Solution {
    public int shipWithinDays(int[] weights, int days) {
        int left = 0, right = 0;
        for (int w : weights) {
            left = Math.max(left, w);
            right += w;
        }

        while (left < right) {
            int mid = (left + right) / 2;
            if (canShip(weights, days, mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        return left;
    }

    private boolean canShip(int[] weights, int days, int capacity) {
        int currentLoad = 0, daysNeeded = 1;
        for (int w : weights) {
            if (currentLoad + w > capacity) {
                daysNeeded++;
                currentLoad = 0;
            }
            currentLoad += w;
        }
        return daysNeeded <= days;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Capacity to Ship Packages in D Days interactively → ← All solutions