> For the complete documentation index, see [llms.txt](https://mayanktyagi3111.gitbook.io/interview-prep/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mayanktyagi3111.gitbook.io/interview-prep/stacks-and-queues/sum-of-subarray-minimums.md).

# Sum of Subarray Minimums

Given an array of integers `A`, find the sum of `min(B)`, where `B` ranges over every (contiguous) subarray of `A`.

Since the answer may be large, **return the answer modulo `10^9 + 7`.**

**Example 1:**

```
Input: [3,1,2,4]
Output: 17
Explanation: Subarrays are [3], [1], [2], [4], [3,1], [1,2], [2,4], [3,1,2], [1,2,4], [3,1,2,4]. 
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.  Sum is 17.
```

**Note:**

1. `1 <= A.length <= 30000`
2. `1 <= A[i] <= 30000`

```java
class Solution {
    public int sumSubarrayMins(int[] A) {
        // We will maintain an increasing stack
        Deque<Integer> stack = new LinkedList<>();
        int[] leftDistance = new int[A.length];
        int[] rightDistance = new int[A.length];

        for (int i = 0; i < A.length; i++) {
            // use ">=" to deal with duplicate elements
            while (!stack.isEmpty() && A[stack.peek()] >= A[i])
                stack.pop();

            leftDistance[i] = stack.isEmpty() ? (i + 1) : (i - stack.peek());
            stack.push(i);
        }
        stack.clear();
        for (int i = A.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && A[stack.peek()] > A[i])
                stack.pop();

            rightDistance[i] = stack.isEmpty() ? (A.length - i) : (stack.peek() - i);
            stack.push(i);
        }

        int ans = 0;
        int mod = 1000000007;
        for (int i = 0; i < A.length; i++)
            // Total number of subarrays with A[i] as min element
            ans = (ans + A[i] * leftDistance[i] * rightDistance[i]) % mod;
        return ans;
    }
}
```
