Data Structures & AlgorithmsVery hardProduct company OA

Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes within D days. What is printed?

Packages must ship in order, one contiguous group per day; binary search on the daily capacity finds the smallest capacity that finishes within D days. What is printed?
def days_needed(w, cap):
    d, cur = 1, 0
    for x in w:
        if cur + x > cap: d += 1; cur = 0
        cur += x
    return d
def min_cap(w, D):
    lo, hi = max(w), sum(w)
    while lo < hi:
        mid = (lo + hi) // 2
        if days_needed(w, mid) <= D: hi = mid
        else: lo = mid + 1
    return lo
w = [7, 2, 5, 10, 8, 1, 6]
print(min_cap(w, 3), min_cap(w, 2), min_cap(w, 7))
  1. A. 15 24 10
  2. B. 14 23 10
  3. C. 15 24 39
  4. D. 13 20 10

Correct answer: A. 15 24 10

days_needed is monotone non-increasing in the capacity, so we can binary search between max(w) (otherwise one package never fits) and sum(w). D = 3: capacity 15 gives [7,2,5] [10] [8,1,6]; 14 needs 4 days. D = 2: 24 gives [7,2,5,10] [8,1,6]. D = 7 (one per package) needs only max(w) = 10. Total O(n log(sum)). 39 ignores that D = 2 still permits a split.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic