907. Sum of Subarray Minimums

907. Sum of Subarray Minimums

Given an array of integers A, find the sum of min(B), where B ranges over every (contiguous) subarray of A.

Since the answer may be large, return the answer modulo 10^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

Approach

需要找规律,找每个数的作用域,也就是这个数的右边第一个小于它的数和左边第一个小于等于它的数

Code

#define modulo 1000000007

class Solution {
public:
    int sumSubarrayMins(vector<int> &A) {
        int n = A.size();
        if (n == 1)
            return A[0];
        stack<pair<int, int>> st;
        vector<int> left(n, -1), right(n, n);
        for (int i = 0; i < n; ++i) {
            while (!st.empty() && st.top().first > A[i]) {
                right[st.top().second] = i;
                st.pop();
            }
            st.push(make_pair(A[i], i));
        }
        while (!st.empty())st.pop();
        for (int i = n - 1; i >= 0; --i) {
            while (!st.empty()&&st.top().first>=A[i]){
                left[st.top().second]=i;
                st.pop();
            }
            st.push(make_pair(A[i],i));
        }
        int sum=0;
        for(int i=0;i<n;i++){
            sum=(sum%modulo+(i-left[i])*(right[i]-i)*A[i]%modulo)%modulo;
        }
        return sum;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值