NeetCode #277LC-1011MediumBinary SearchNC 250
← Back to All Problems#277 · #1011 · Capacity To Ship Packages Within D Days(在 D 天内送达包裹的能力)
📌 Problem Statement & Constraints
A conveyor belt has packages with weights
weights[i] that must be shipped within days days, in the given order. Each day a ship carries packages in order until the weight limit is reached. Return the minimum ship capacity. Constraints: 1 <= days <= weights.length <= 5 * 10^4, 1 <= weights[i] <= 500.💡 Core Algorithmic Approaches
- Binary search on the capacity. The predicate "can ship within
daysdays with capacityc" is monotone. - The lower bound is
max(weights), since a single package must fit; the upper bound issum(weights), which ships everything in one day. - For a given capacity, greedily fill each day and count the days used.
- Use
hi = midwhen feasible, sincemidmay itself be the answer.
💻 Benchmark Python3 Implementation
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
lo, hi = max(weights), sum(weights)
while lo < hi:
mid = (lo + hi) // 2
used = 1 # days needed at capacity mid
cur = 0
for w in weights:
if cur + w > mid:
used += 1 # start a new day
cur = 0
cur += w
if used <= days:
hi = mid # feasible -> try smaller
else:
lo = mid + 1
return lo⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n log(sum(weights))): each predicate is O(n) and there are O(log V) of them.
💾 Space Complexity
O(1): a few scalars.
⚠️ Interview Pitfalls & Follow-ups
- Setting the lower bound to 1: a capacity below
max(weights)can never work, so the search would waste iterations (and the greedy would still count correctly, but the range is tighter withmax). - Using
hi = mid - 1when feasible: could skip the optimum; usehi = mid. - Forgetting that the order is fixed: packages must be shipped in order, which is what makes the greedy day-filling valid. Sorting would break the problem.
- Counting days as
ceil(sum / mid): the order and indivisibility of packages make the actual count larger.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Binary Search Problems
中文速览与面试要点
在 D 天内送达包裹的能力
传送带上的包裹必须在 days 天内从一个港口运送到另一个港口。传送带上的第 i 个包裹的重量为 weights[i] 。每一天,我们都会按给出重量(weights)的顺序往传送带上装载包裹。我们装载的重量不会超过船的最大运载重量。返回能在 days 天内将传送带上的所有包裹送达的船的 最低 运载能力。约束:1 ≤ days ≤ weights.length ≤ 5 × 10^4;1 ≤ weights[i] ≤ 500。
核心要点
- 二分答案(标准解) :船的载重范围是 [max(weights), sum(weights)] ——下界必须能装下单件最重的包裹,上界为一次装完。
- 单调性 :载重越大,所需天数越少(非严格),因此可以二分。
- 判定函数 feasible(cap) :贪心地按顺序装货,累加到超过 cap 就开新的一天。返回所需天数。
- 为什么贪心正确 :包裹必须按顺序装载,因此「能装就装」是唯一可行的策略,也是最优的(推迟装载只会增加天数)。
常见陷阱
- 下界写成 1 或 0 :会导致单件包裹超过载重时无法运输,判定函数失效(cur 永远装不下)。下界必须是 max(weights) 。
- 判定函数中忘记「至少一天」 : d 的初值应为 1。
- 装不下时忘记重置 cur = 0 :会把上一个包裹的重量带到新的一天,导致天数偏少。
- 在 cur + w > cap 时直接 d += 1 但不处理 w :必须先重置 cur 再累加 w,顺序不能错。
- 二分模板方向写反 :本题求「最低可行载重」,应写 if feasible: r = mid else: l = mid + 1 。
参考实现
class Solution:
def shipWithinDays(self, weights: list[int], days: int) -> int:
def days_needed(cap: int) -> int:
d = 1 # 至少需要一天
cur = 0
for w in weights:
if cur + w > cap: # 装不下 -> 开新的一天
d += 1
cur = 0
cur += w
return d
l, r = max(weights), sum(weights)
while l < r:
mid = (l + r) // 2
if days_needed(mid) <= days:
r = mid # 可行 -> 尝试更小的载重
else:
l = mid + 1
return l