#907

Sum of Subarray Minimums

Medium Monotonic stack contribution

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Sum the minimum of every contiguous subarray, modulo 1e9+7.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: add up the minimum of every subarray.

Why this works: count how many subarrays have arr[i] as their minimum: (distance to previous smaller) × (distance to next smaller-or-equal).

Example: [3, 1, 2, 4]

3: 1×1 → 3, 1: 2×3 → 6, 2: 1×2 → 4, 4: 1×1 → 4total 17

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using strict < on both sides, which double-counts subarrays with repeated minimums.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Stack & Queue
🎬 Episodes 46–52: video coming soon