907. Sum of Subarray Minimums
阿新 • • 發佈:2020-08-15
Given an array of integersA
, find the sum ofmin(B)
, whereB
ranges overevery (contiguous) subarray ofA
.
Since the answer may be large,return the answer modulo10^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
class Solution { public int sumSubarrayMins(int[] A) { int len = A.length; Stack<Integer> stack = newStack<>(); int[] left = new int[len]; int[] right = new int[len]; for(int i = 0; i < A.length; i++) { left[i] = i + 1; right[i] = len - i; } // previous less element for(int i = 0; i < len; i++){ while(!stack.isEmpty() && A[stack.peek()] > A[i]) { stack.pop(); } left[i]= stack.isEmpty() ? i + 1 : i - stack.peek(); stack.push(i); } //next less element stack = new Stack<>(); for(int i = 0; i < len; i++){ while(!stack.isEmpty() && A[stack.peek()] > A[i]) { right[stack.peek()] = i - stack.peek(); stack.pop(); } stack.push(i); } int ans = 0; int mod = (int)1e9 + 7; for(int i = 0; i < len; i++) { ans = (ans + A[i] * left[i] * right[i]) % mod; } return ans; } }
https://www.cnblogs.com/grandyang/p/8887985.html
monotonic stack