Data Structures & AlgorithmsVery hardProduct company OA

What is the sum of min(subarray) over all contiguous subarrays of [2, 5, 1, 4, 3]? (A monotonic stack counts, for each element, how many subarrays it is the minimum of.)

  1. A. 15
  2. B. 28
  3. C. 25
  4. D. 31

Correct answer: B. 28

a[i] is the minimum of (choices of left end) × (choices of right end) subarrays, extending until a smaller element. 2: 1 × 2 → 2·2 = 4; 5: 1 × 1 → 5; 1: 3 × 3 → 9; 4: 1 × 1 (3 to its right is smaller) → 4; 3: 2 × 1 (it can extend left over 4) → 6. Total 4 + 5 + 9 + 4 + 6 = 28. Summing the elements once (15) ignores that each element is the minimum of several subarrays.

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

Exams that ask this topic