1. 程式人生 > 實用技巧 >907. Sum of Subarray Minimums

907. Sum of Subarray Minimums

Given an array of integersA, find the sum ofmin(B), whereBranges 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. 1 <= A.length <= 30000
  2. 1 <= A[i] <= 30000

https://leetcode.com/problems/sum-of-subarray-minimums/discuss/178876/stack-solution-with-very-detailed-explanation-step-by-step

class Solution {
    public int sumSubarrayMins(int[] A) {
        int len = A.length;
        Stack<Integer> stack = new
Stack<>(); 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