Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most ops operations, minimise the largest bag. Binary search on the answer: a bag of b needs (b − 1) // cap splits.

Problem: Bags hold balls; an operation splits one bag into two bags (any sizes). With at most `ops` operations, minimise the largest bag. Binary search on the answer: a bag of b needs (b − 1) // cap splits.
def min_penalty(bags, ops):
    lo, hi = 1, max(bags)
    while lo < hi:
        mid = (lo + hi) // 2
        if sum((b - 1) // mid for b in bags) <= ops: hi = mid
        else: lo = mid + 1
    return lo
print(min_penalty([9, 4, 7], 3), min_penalty([20], 4), min_penalty([3, 3, 3], 0))
What is printed?
  1. A. 4 4 1
  2. B. 4 4 3
  3. C. 3 4 3
  4. D. 4 5 3

Correct answer: B. 4 4 3

To make every bag ≤ cap, a bag of b balls must become ⌈b / cap⌉ bags, i.e. (b − 1) // cap splits; feasibility is monotone in cap. cap = 4: 2 + 0 + 1 = 3 ≤ 3 ✓; cap = 3: 2 + 1 + 2 = 5 ✗ → 4. [20] with 4 splits → 5 bags of 4. Halving the biggest bag each time (a heap greedy) is wrong: [9] with 2 splits goes 9 → 5 + 4 → 3 + 2 + 4 (max 4), while 3 + 3 + 3 achieves 3. O(n log max).

More Coding Interview Problems questions

Exams that ask this topic