Capacity To Ship Packages Within D Days - Problem

A conveyor belt has packages that must be shipped from one port to another within days days.

The i-th package on the conveyor belt has a weight of weights[i]. Each day, we load the ship with packages on the conveyor belt (in the order given by weights). We may not load more weight than the maximum weight capacity of the ship.

Return the least weight capacity of the ship that will result in all the packages on the conveyor belt being shipped within days days.

Input & Output

Example 1 — Basic Case
$ Input: weights = [1,2,3,1,1], days = 4
Output: 6
💡 Note: Ship capacity 6: Day 1 [1,2,3] (6 units), Day 2 [1] (1 unit), Day 3 [1] (1 unit). Total 3 days ≤ 4.
Example 2 — Tight Constraint
$ Input: weights = [3,2,2,4,1,4], days = 3
Output: 6
💡 Note: Ship capacity 6: Day 1 [3,2] (5 units), Day 2 [2,4] (6 units), Day 3 [1,4] (5 units). Exactly 3 days.
Example 3 — Single Heavy Package
$ Input: weights = [1,2,3,4,5,6,7,8,9,10], days = 5
Output: 15
💡 Note: Ship capacity 15 allows balanced distribution across 5 days to handle all packages efficiently.

Constraints

  • 1 ≤ days ≤ weights.length ≤ 5 × 104
  • 1 ≤ weights[i] ≤ 500

Visualization

Tap to expand
Capacity To Ship Packages Within D Days INPUT 1 2 3 1 1 SHIP Input Values weights = [1,2,3,1,1] days = 4 Total weight = 8 Max single = 3 ALGORITHM STEPS 1 Set Search Range left=3 (max weight) right=8 (sum weights) 2 Binary Search mid = (left+right)/2 Check if feasible 3 Count Days Needed Simulate loading Count required days 4 Adjust Range days OK: right = mid days fail: left = mid+1 [3]--[4]--[5]--[6]--[7]--[8] Binary Search on Capacity FINAL RESULT Capacity = 6 Shipping Schedule: Day 1 [1,2,3] = 6 Day 2 [1] = 1 Day 3 [1] = 1 3 days OK! Output 6 Key Insight: Binary search on the answer! The minimum capacity must be at least max(weights) and at most sum(weights). For each capacity mid, simulate greedy loading to count days. If days needed is within limit, try smaller capacity. TutorialsPoint - Capacity To Ship Packages Within D Days | Binary Search Approach
Asked in
Amazon 45 Google 35 Facebook 25 Microsoft 20
89.7K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen