Data Structures & AlgorithmsVery hardProduct company OA

Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is printed?

Sum over all subarrays of (max − min), computed as Σ max − Σ min with two monotonic-stack passes, checked against brute force. What is printed?
def spread(a):
    n = len(a); total = 0
    for sign in (1, -1):
        b = [sign * x for x in a]; st = []; left = [0] * n
        for i in range(n):
            while st and b[st[-1]] < b[i]: st.pop()
            left[i] = i - (st[-1] if st else -1); st.append(i)
        st = []; right = [0] * n
        for i in range(n - 1, -1, -1):
            while st and b[st[-1]] <= b[i]: st.pop()
            right[i] = (st[-1] if st else n) - i; st.append(i)
        total += sum(b[i] * left[i] * right[i] for i in range(n))
    return total
a = [4, 1, 3, 2]
print(spread(a), sum(max(a[i:j]) - min(a[i:j]) for i in range(4) for j in range(i + 1, 5)))
  1. A. 14 14
  2. B. 14 12
  3. C. 12 12
  4. D. 17 14

Correct answer: A. 14 14

Negating the array turns 'contribution as minimum' into 'contribution as maximum', so one routine computes both: Σ max = 4+4+4+4+1+3+3+3+3+2 = 31, Σ min = 4+1+1+1+1+1+1+3+2+2 = 17, difference 14 – the same as the brute force. The ≤ vs < tie-breaking on the two sides is what keeps equal values from being counted twice. O(n) instead of O(n²).

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

Exams that ask this topic