Skip to content

Sum of Subarray Minimums⚓︎

Link

Description⚓︎

Given an array of integers arr, find the sum of min(b), where b ranges over every (contiguous) subarray of arr. Since the answer may be large, return the answer modulo 10^9 + 7.

Example 1:

  • Input: arr = [3,1,2,4]
  • Output: 17
  • Explanation:
1
2
3
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.

Example 2:

  • Input: arr = [11,81,94,43,3]
  • Output: 444

Constraints:

  • 1 <= arr.length <= 3 * 10^4
  • 1 <= arr[i] <= 3 * 10^4

Solution⚓︎

class Solution {
public:
    int sumSubarrayMins(vector<int>& arr) {
        const int MOD = 1e9 + 7;
        long res = 0L;
        stack<int> stk;
        for (int i = 0; i < arr.size(); i++) {
            while (!stk.empty() && arr[stk.top()] >= arr[i]) {
                int current = stk.top();
                stk.pop();
                int left = !stk.empty() ? stk.top() : -1;
                res += (current - left) * (i - current) * arr[current];
            }
            stk.push(i);
        }

        while (!stk.empty()) {
            int current = stk.top();
            stk.pop();
            int left = !stk.empty() ? stk.top() : -1;
            res += (current - left) * (arr.size() - current) * arr[current];
        }

        return res % MOD;
    }
};
  • Time complexity: \(O(n)\);
  • Space complexity: \(O(n)\).