mediumMonotonic StackDynamic ProgrammingStack

Sum of Subarray Minimums

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

Recognize the pattern

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

Brute force idea

A straightforward first read of Sum of Subarray Minimums is this: 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.

Better approach

A calmer way to see Sum of Subarray Minimums is this: 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.

Key invariant

The truth you want to protect throughout Sum of Subarray Minimums is this: 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.

Watch out for

One easy way to drift off course in Sum of Subarray Minimums is this: 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