Home LeetCode - 907. Sum of Subarray Minimums
Post
Cancel

LeetCode - 907. Sum of Subarray Minimums

907. Sum of Subarray Minimums - medium

문제

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.

제한사항

  • 1 <= A.length <= 30000
  • 1 <= A[i] <= 30000

입출력 예

1
2
3
4
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.

풀이

  • Array, Stack
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
28
29
30
31
32
33
34
35
// 분석 필요
class RepInteger{
public:         
    RepInteger(int v, int c) : val(v), count(c) {}
    int val, count;
};

class Solution {
public:
    int sumSubarrayMins(vector<int>& A) {
        int ans = 0, dot = 0;
        int n = A.size(), mod = 1e9 + 7;
        stack<RepInteger> s;

        for (int i = 0; i < n; ++i) {
            // Add all answers for subarrays [i, j], i <= j
            int count = 1;
            while (!s.empty() && s.top().val >= A[i]) {
                RepInteger node = s.top();
                s.pop();
                
                count += node.count;
                dot -= node.val * node.count;
            }
            
            s.push(RepInteger(A[i], count));
            
            dot += A[i] * count;
            ans += dot;
            ans %= mod;
        }
   
        return ans;
    }
};
This post is licensed under CC BY 4.0 by the author.