Count The Minimum Once

Given an array of nn integers, compute the sum of the minimum of every contiguous subarray. There are n(n+1)2\frac{n(n+1)}{2} subarrays and nn can be 2⋅1052 \cdot 10^5, so enumerating them is out.

Which reframing is the one that opens the problem?

A

Binary search on the answer, checking for a candidate total whether it is achievable.

B

Stop iterating over subarrays and iterate over elements: for each aia_i, count how many subarrays have aia_i as their minimum, then add ai×countia_i \times \text{count}_i. Each count is (distance to the nearest smaller element on the left) times (distance to the nearest smaller element on the right), both computable in one pass with a monotonic stack.

C

Sort the array ascending, then process elements in order so the current element is always the minimum of what remains.

D

Keep the subarray loop but maintain a running minimum so each subarray costs O(1)O(1) instead of O(n)O(n), which brings the total to O(n2)O(n^2).