Data Structures & AlgorithmsVery hardProduct company OA

Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack and prefix sums, checked against brute force.

Problem: For every contiguous block, score = (minimum of the block) × (sum of the block). Return the maximum score using a monotonic stack and prefix sums, checked against brute force.
def min_product(a):
    n = len(a); P = [0]
    for x in a: P.append(P[-1] + x)
    left, st = [0] * n, []
    for i in range(n):
        while st and a[st[-1]] >= a[i]: st.pop()
        left[i] = st[-1] + 1 if st else 0; st.append(i)
    right, st = [0] * n, []
    for i in range(n - 1, -1, -1):
        while st and a[st[-1]] >= a[i]: st.pop()
        right[i] = st[-1] - 1 if st else n - 1; st.append(i)
    return max(a[i] * (P[right[i] + 1] - P[left[i]]) for i in range(n))
a = [3, 1, 5, 6, 4, 2]
print(min_product(a), max(min(a[i:j]) * sum(a[i:j]) for i in range(6) for j in range(i + 1, 7)))
What is printed?
  1. A. 60 60
  2. B. 72 60
  3. C. 60 72
  4. D. 36 36

Correct answer: A. 60 60

For each a[i] as the minimum, extend the block as far as possible on both sides while values stay ≥ a[i]: positive numbers make the sum only larger. The stack gives the boundaries in O(n), prefix sums give the block sum. a[i] = 4 → block [5, 6, 4] sum 15 → 60; a[i] = 5 → [5, 6] → 55; a[i] = 1 → whole array 21. Best 60, equal to brute force. Ties use ≥ on both sides here, which is safe because a tie only produces the same candidate twice.

More Coding Interview Problems questions

Exams that ask this topic