← All Exercises

Binary Search on Ship Capacity

advancedgo~30min

Background

When feasibility is monotone in the answer, binary search over capacity avoids enumerating assignments; the lower bound is the heaviest package and the upper bound is the total weight.

Problem

Given package weights that must ship in order and a day limit, return the minimum ship capacity that moves all packages within the limit. A package cannot be split, each day carries a contiguous group, and weights are positive.

Input

A list of positive package weights and a positive day limit.

Output

The minimum feasible capacity, or an error for empty weights, invalid days, or non-positive package weights.

Sample tests

Sample 1

Input: weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days = 5
Expected: 15

Sample 2

Input: weights = [3, 2, 2, 4, 1, 4], days = 3
Expected: 6

Sample 3

Input: weights = [5], days = 1
Expected: 5

Your solution

Learning objective

Recognize monotone feasibility and binary search a numeric answer space with greedy simulation.