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 <= A.length <= 30000
1 <= A[i] <= 30000
classSolution {publicintsumSubarrayMins(int[] A) {// We will maintain an increasing stackDeque<Integer> stack =newLinkedList<>();int[] leftDistance =newint[A.length];int[] rightDistance =newint[A.length];for (int i =0; i <A.length; i++) {// use ">=" to deal with duplicate elementswhile (!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; }}