Data Structures & AlgorithmsVery hardProduct company OA

Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with asymmetric tie-breaking, gives O(n).

Problem: For n = 2·10⁵, compute Σ over all subarrays of (max − min). Sum of maxima minus sum of minima, each via monotonic stacks with asymmetric tie-breaking, gives O(n).
def sum_ranges(a):
    n = len(a)
    def total(better):
        left = [0] * n; right = [0] * n; st = []
        for i in range(n):
            while st and better(a[i], a[st[-1]]): st.pop()
            left[i] = i - (st[-1] if st else -1); st.append(i)
        st = []
        for i in range(n - 1, -1, -1):
            while st and (better(a[i], a[st[-1]]) or a[i] == a[st[-1]]): st.pop()
            right[i] = (st[-1] if st else n) - i; st.append(i)
        return sum(a[i] * left[i] * right[i] for i in range(n))
    return total(lambda x, y: x > y) - total(lambda x, y: x < y)
def brute(a):
    return sum(max(a[i:j]) - min(a[i:j]) for i in range(len(a)) for j in range(i + 1, len(a) + 1))
print(sum_ranges([4, 1, 3, 3]), brute([4, 1, 3, 3]), sum_ranges([2, 5, 1]), brute([2, 5, 1]))
What is printed?
  1. A. 13 13 11 11
  2. B. 13 10 11 11
  3. C. 13 13 9 11
  4. D. 16 13 11 11

Correct answer: A. 13 13 11 11

Each a[i] is the maximum of left[i]·right[i] subarrays (and similarly the minimum), so Σ(max − min) = Σ a[i]·(count as max − count as min). Equal values (the two 3s) must be assigned to exactly one of them: strict on one side, non-strict on the other. [2, 5, 1]: ranges 0, 0, 0, 3, 4, 4 → 11. Brute force is O(n²) at best (O(n³) as written), far too slow for 2·10⁵.

More Coding Interview Problems questions

Exams that ask this topic