Minimum Load Capacity to Deliver Parcels Within a Deadline

Implement minShipCapacity

A delivery truck must carry a line of parcels — weights[i] is the weight of the i-th parcel — in the given order, never splitting a single parcel across trips. Given a fixed days limit, find the smallest truck capacity that finishes delivering every parcel within that many trips. Each trip loads parcels one after another until the next one would exceed the truck's capacity, then starts a fresh trip. No capacity below the heaviest single parcel could ever work (that parcel wouldn't fit at all), and a capacity equal to the total weight always finishes in a single trip — so the answer is guaranteed to fall somewhere between those two bounds. The number of trips needed only ever decreases (or stays flat) as capacity grows, which makes this a binary search on the answerBinary Search on the AnswerInstead of searching a sorted array, the search runs directly over the space of possible answers (here, every candidate truck capacity). It works whenever "is this candidate good enough?" is monotonic — once a candidate works, every larger candidate keeps working too. — search directly over candidate capacities rather than trying to reason about trip splits directly.

Example 1:

Input: weights = [14,6,9,17,4], days = 4

Output: 17

Example 2:

Input: weights = [6,11,4,9,2,8], days = 3

Output: 17

Example 3:

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

Output: 7

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ number of parcels ≤ 5 × 10⁴
  • 1 ≤ weights[i] ≤ 500
  • 1 ≤ days ≤ number of parcels

weights =

[14, 6, 9, 17, 4]

days =

4