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))- A. 15 24 10
- B. 14 23 10
- C. 15 24 39
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Minimum window of s containing every character of t WITH multiplicity, using a need-counter. What is printed? python from collections…
- Shortest subarray with sum ≥ 5 in an array WITH negative numbers: an increasing deque of prefix-sum indices versus the usual shrinking…
- Probe-sequence coverage for open addressing: how many distinct slots can the offsets i² (quadratic) and i(i+1)/2 (triangular) reach in…
- An LRU cache of capacity 3 (OrderedDict, oldest first) processes page requests. How many misses, and what is the final order? python from…
- Minimum number of brackets to INSERT to make a string balanced, returned as (total, unmatched ')', unmatched '('). What is printed? python…
- Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed? python def vote(a): cand…