Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in different positions are separate subarrays.

Compute the sum over all subarrays of the minimum element, for a = [3, 1, 2, 1, 3]. Subarrays are counted by position, so equal values in different positions are separate subarrays.
a=[3,1,2,1,3]
print(sum(min(a[i:j+1]) for i in range(len(a)) for j in range(i,len(a))))
What is printed?
  1. A. 10
  2. B. 37
  3. C. 20
  4. D. 23

Correct answer: C. 20

For each element count the subarrays where it is the minimum, strict on one side and non-strict on the other so equal values are not double counted. Summing maxima answers a different question, and dropping length-one subarrays removes single elements.

More Coding Interview Problems questions

Exams that ask this topic