Skip to content

visual walkthrough

Sum of Subarray Minimums

Counts each element's contribution using previous/next smaller elements.

Solve on LeetCode

The idea

Flip the question: instead of finding the minimum of every subarray, count how many subarrays each number is the minimum of.

A monotonic stack finds the nearest smaller value on each side, which bounds where those subarrays can start and end.

Complexity

approachtimespace
Every subarrayO(n²)O(1)
Contribution with monotonic stacksO(n)O(n)

More walkthroughs