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?- A. 60 60
- B. 72 60
- C. 60 72
- 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
- Problem: Find the shortest substring of s that contains t as a SUBSEQUENCE (leftmost if several). Two pointers: scan forward to complete…
- Problem: Count monotone paths (right/down) in a grid with blocked cells. The first version builds the table as [[0] C] R – every row is…
- Problem: Two versions of Dijkstra. The second marks a vertex as finished the moment it is first PUSHED and never updates it again. python…
- Problem: KMP pattern search instrumented to count fallback steps k = π[k − 1] (total over the whole text). What is printed (matches…
- Problem: Single machine, jobs (name, duration, due time); lateness = finish − due. Minimise the MAXIMUM lateness. Compare…
- Problem: Two sorted price lists; list the 6 smallest sums a[i] + b[j] without generating all pairs (heap of frontier cells with a…