Problem 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 109 + 7.

 

Example 1:

Input: arr = [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.

Example 2:

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

 

Constraints:

  • 1 <= arr.length <= 3 * 104
  • 1 <= arr[i] <= 3 * 104

Solution


Python3

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        N = len(arr)
        MOD = 10 ** 9 + 7
        prevSmaller = [-1] * N
        nextSmaller = [N] * N
        res = 0
 
        # construct nextSmaller array
        stack = []
        for i, x in enumerate(arr):
            while stack and x < arr[stack[-1]]:
                nextSmaller[stack.pop()] = i
            
            stack.append(i)
        
        # construct prevSmaller array
        stack = []
        for i in range(N - 1, -1, -1):
            # less than or equal here to prevent double counting
            while stack and arr[i] <= arr[stack[-1]]:
                prevSmaller[stack.pop()] = i
            
            stack.append(i)
        
        for i, x in enumerate(arr):
            # fix x as the smallest in the subarray
            left = i - prevSmaller[i]
            right = nextSmaller[i] - i
            res += x * left * right
            res %= MOD
        
        return res