Skip to content

Commit 01875b3

Browse files
authored
Create sum-of-subarray-minimums.cpp
1 parent b2db73f commit 01875b3

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/sum-of-subarray-minimums.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// Ascending stack solution
5+
class Solution {
6+
public:
7+
int sumSubarrayMins(vector<int>& A) {
8+
static const int M = 1e9 + 7;
9+
10+
vector<int> left(A.size());
11+
stack<pair<int, int>> s1;
12+
for (int i = 0; i < A.size(); ++i) {
13+
int count = 1;
14+
while (!s1.empty() && s1.top().first > A[i]) {
15+
count += s1.top().second;
16+
s1.pop();
17+
}
18+
s1.emplace(A[i], count);
19+
left[i] = count;
20+
}
21+
22+
vector<int> right(A.size());
23+
stack<pair<int, int>> s2;
24+
for (int i = A.size() - 1; i >= 0; --i) {
25+
int count = 1;
26+
while (!s2.empty() && s2.top().first >= A[i]) {
27+
count += s2.top().second;
28+
s2.pop();
29+
}
30+
s2.emplace(A[i], count);
31+
right[i] = count;
32+
}
33+
34+
int result = 0;
35+
for (int i = 0; i < A.size(); ++i) {
36+
result = (result + A[i] * left[i] * right[i]) % M;
37+
}
38+
return result;
39+
}
40+
};

0 commit comments

Comments
 (0)