Skip to main content
Back to problems
Leetcode
Medium
Arrays
Binary Search
Greedy
Amazon
Capacity To Ship Packages Within D Days

Find the minimum ship capacity needed to deliver all packages within a fixed number of days while keeping package order unchanged.

Acceptance 0%
Problem Statement

You are given an array of package weights, where each weight represents the mass of one package in the order it must be loaded. A ship loads packages in that same order, and on each day it can carry a contiguous sequence of packages whose total weight does not exceed its capacity.

Your task is to determine the minimum ship capacity needed so that all packages can be shipped within exactly or at most DD days.

Because the packages must be loaded in order, you cannot reorder them to make shipping easier. If the capacity is too small, shipping will take too many days; if it is large enough, all packages can be delivered on time.

Input Format

Input

  • An integer array weights where weights[i] is the weight of the ii-th package.
  • An integer days representing the maximum number of days allowed.

Assumptions

  • Packages must be shipped in the given order.
  • Each day, the ship can load a contiguous prefix of the remaining packages until adding the next package would exceed the ship capacity.

Output Format

Output

  • Return the minimum integer ship capacity that allows all packages to be shipped within days days.

Constraints

  • 1weights.length5×1041 \le weights.length \le 5 \times 10^4
  • 1weights[i]5×1041 \le weights[i] \le 5 \times 10^4
  • 1daysweights.length1 \le days \le weights.length
  • The answer fits in a 32-bit signed integer.
Examples
Sample cases returned by the problem API.

Example 1

Input

weights = [1,2,3,1,1], days = 4

Output

3

Explanation

With capacity 3, the ship can load [1,2], [3], [1,1], and then one package per day if needed; all packages are delivered within 4 days. A smaller capacity would require more than 4 days.

Example 2

Input

weights = [3,2,2,4,1,4], days = 3

Output

6

Explanation

One optimal loading plan is [3,2], [2,4], [1,4]. Each day's load is at most 6, so 6 is the minimum feasible capacity.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.