1056. Capacity To Ship Packages Within D Days
My accepted Python solution to LeetCode problem 1056, Capacity To Ship Packages Within D Days, running in 189ms.
- Difficulty: Medium
- Python
- Runtime 189ms
- Memory 21.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 189ms, memory 21.9MB, accepted 2026-01-02.
class Solution:
def shipWithinDays(self, weights: List[int], days: int) -> int:
def can_ship(capacity):
current_load = 0
days_needed = 1
for w in weights:
if current_load + w > capacity:
days_needed += 1
current_load = w
else:
current_load += w
return days_needed <= days
# Binary search between max weight and sum of weights
left = max(weights)
right = sum(weights)
while left < right:
mid = (left + right) // 2
if can_ship(mid):
right = mid
else:
left = mid + 1
return left