Example - Capacity to Ship Packages

Another binary search on the answer problem.

Problem: Ship packages over DD days. Find minimum capacity.

Approach: Binary search on capacity [max(weights),(weights)][\max(weights), \sum(weights)]. For each capacity, simulate loading and count days.

function shipWithinDays(weights, D):
    low = max(weights)
    high = sum(weights)
    while low < high:
        mid = (low + high) / 2
        if canShip(weights, mid, D):
            high = mid
        else:
            low = mid + 1
    return low

Time: O(nlog(weights))O(n \log(\sum weights)). Space: O(1)O(1).