mediumMonotonic StackDynamic ProgrammingStack

Sum of Subarray Minimums

mediumTime: O(n)Space: O(n)

Signals to notice

sum of minimums of all subarrayscontribution of each element as minimumnext/previous smaller

Brute force first

Enumerate all subarrays, find each minimum. Each subarray independently finds its minimum. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

For each element, count how many subarrays it's the minimum of. Use monotonic stacks to find the distance to the previous and next smaller elements. Contribution = nums[i] × left × right. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

Element nums[i] is the minimum of all subarrays starting in [prevSmaller+1, i] and ending in [i, nextSmaller-1]. The count of such subarrays is left × right, where left and right are the distances to the boundaries. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Handling equal elements — use strict < on one side and ≤ on the other to avoid double-counting subarrays where multiple elements share the minimum value. The fix is usually to return to the meaning of each move, not just the steps themselves.

Stack Pattern