Module 6 · Stacks and Queues · Sum of Subarray Ranges

Sum of subarray minimums

Don't list the subarrays — count, for each value, how many subarrays it's the minimum of. That's every subarray between the closest smaller value on its left and on its right: (p − left) × (right − p) of them. One stack pass finds both sides.

While counting, the window on arr is every subarray arr[i] is the minimum of. On the stack values never decrease from bottom to top, with the index under each. left and right hold the index of the closest smaller value on each side (-1 or n if none).