Leetcode 907:子数组的最小值之和

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

Leetcode 907:子数组的最小值之和

来源:Leetcode

标签:

参考资料:

相似题目:

题目

给定一个整数数组 A,找到 min(B) 的总和,其中 B 的范围为 A 的每个(连续)子数组。
由于答案可能很大,因此返回答案模 10^9 + 7。

输入样例

[3,1,2,4]

输出样例

17

样例解释

子数组为 [3],[1],[2],[4],[3,1],[1,2],[2,4],[3,1,2],[1,2,4],[3,1,2,4]。
最小值为 3,1,2,4,1,1,2,1,1,1,和为 17。

参考代码

class Solution {
public:
    int sumSubarrayMins(vector<int>& A) {
    	int mod=1e9+7;
        long long ans=0;
        for(int i=0;i<A.size();i++){
            int l=i-1, r=i+1;
            long long suml=0,sumr=0;
            while(l>=0 && A[l]>=A[i]){
                suml++;
                l--;
            }
            while(r<A.size() && A[r]>A[i]){
                sumr++;
                r++;
            }
            ans=(ans+((1+suml+sumr+suml*sumr)*A[i])%mod)%mod;
        }
        return (int)ans;
    }

};

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/88381940