⬅ Previous Topic
Find the Smallest Divisor Given a ThresholdNext Topic ⮕
Kth Missing Positive Number⬅ Previous Topic
Find the Smallest Divisor Given a ThresholdNext Topic ⮕
Kth Missing Positive NumberTopic Contents
You are given an array of package weights and a number D
representing the number of days within which all the packages must be delivered. Each day, you can ship packages in the given order, but the total weight of the packages shipped on a day cannot exceed a certain ship capacity.
Your task is to determine the minimum weight capacity of the ship so that all packages can be shipped within D
days.
Note: Packages must be shipped in order and cannot be split.
low = max(weights)
and high = sum(weights)
.low ≤ high
:mid = (low + high) / 2
.D
days using mid
as the capacity.mid
as answer and try to minimize (high = mid - 1
).low = mid + 1
).def shipWithinDays(weights, D):
def canShip(capacity):
days = 1
total = 0
for weight in weights:
if total + weight > capacity:
days += 1 # Need an extra day
total = 0 # Start new day
total += weight
return days <= D
low = max(weights) # Minimum capacity must be at least the max weight
high = sum(weights) # Maximum capacity is sum of all weights (one day)
result = high
while low <= high:
mid = (low + high) // 2
if canShip(mid):
result = mid
high = mid - 1
else:
low = mid + 1
return result
weights = [1,2,3,4,5,6,7,8,9,10]
D = 5
print("Minimum capacity:", shipWithinDays(weights, D))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | When the optimal capacity is found early in the binary search range and only a single pass over weights is needed to validate. |
Average Case | O(n * log(sum - max)) | Binary search runs over the capacity range and for each capacity, we do a full scan of weights. |
Average Case | O(n * log(sum - max)) | In the worst case, binary search tries nearly all capacity values between max(weights) and sum(weights). |
O(1)
Explanation: No extra space is used except a few variables for computation.
⬅ Previous Topic
Find the Smallest Divisor Given a ThresholdNext Topic ⮕
Kth Missing Positive NumberYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.