leetcode907.SumofSubarrayMinimums

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011732358/article/details/83751016

题目:给定正整数数组A,求出A中所有连续子序列的最小值之和mod (10^9 + 7)。
别人思路:对于A中的每一个值A[i],寻找以它为最小值的子序列的数量。也就是说,我们需要寻找A[i]左侧第一个比它大的值的位置,以及右侧第一个比它大的值的位置。然后就可以计算对应的子序列的数量了。

class Solution {
    public int sumSubarrayMins(int[] A) {
        int sum = 0 ;
        Stack<int[]> s1 = new Stack<int[]>() ;
        Stack<int[]> s2 = new Stack<int[]>() ;
        int len = A.length ;
        int left[] = new int[len] ;
        int right[] = new int[len] ;
        for(int i=0;i<len;i++){
            int count = 1 ;
            while(!s1.empty()&&s1.peek()[0]>A[i]){
                count += s1.pop()[1] ;
            }
            s1.push(new int[]{A[i], count}) ;
            left[i] = count ;
        }
        for(int i=len-1;i>=0;i--){
            int count = 1 ;
            while(!s2.empty()&&s2.peek()[0]>=A[i]){
                count += s2.pop()[1] ;
            }
            s2.push(new int[]{A[i], count}) ;
            right[i] = count ;
        }
        for(int i=0;i<len;i++){
            sum = (sum + left[i]*right[i]*A[i])%1000000007 ;
        }
        return sum ;
    }
}

猜你喜欢

转载自blog.csdn.net/u011732358/article/details/83751016