leetcode907.SumofSubarrayMinimums

题目:给定正整数数组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 ;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值