Tuesday, July 9, 2019

LeetCode [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. 1 <= A.length <= 30000
  2. 1 <= A[i] <= 30000
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution
{
    const int mod = 1e9+7;
  public:
    int sumSubarrayMins(vector<int> &A)
    {
        stack<pair<int, int>> stk; //val, count(#subset(ending at val) with min(subset)==val)
        int sum = 0;
        int partialSum = 0;//sum of min(B) ending at a
        for (auto a : A)//consider all subsets ending at 'a'
        {
            int count = 1;//min({a})==a, so count = 1 
            while (!stk.empty() && a < stk.top().first)
            {
                pair<int, int> vc = stk.top();
                stk.pop();
                partialSum -= vc.first * vc.second;
                count += vc.second;
            }
            stk.push(pair<int, int>(a, count));
            partialSum += a * count;
            sum += partialSum;
            sum %= mod;
        }
        return sum;
    }
};

No comments:

Post a Comment