MediumArrayBinary SearchGreedy

Capacity To Ship Packages Within D Days

LeetCode
1 approach, code in all languages

A conveyor belt feeds a ship a sequence of packages, each with a known weight. Every day the ship is loaded with packages taken from the front of the belt in their given order, and the combined weight loaded on any single day cannot exceed the ship's capacity. The order of packages is fixed and cannot be rearranged.

Given the list of weights and a target number of days, find the smallest ship capacity that still allows every package to be shipped within that many days.

Example 1

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

Output: 15

With capacity 15 the loads can be (1..5), (6,7), (8), (9), (10) across five days. Any smaller capacity forces a sixth day.

Example 2

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

Output: 8

Capacity 8 lets each day carry two boxes: (4,4) and (4,4). Capacity 7 would require three days.

Constraints

  • 1 <= days <= weights.length <= 5 * 10^4
  • 1 <= weights[i] <= 500
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now