Skip to content

Commit

Permalink
Create sum-of-subarray-minimums.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 16, 2018
1 parent d9529cd commit 6ca484e
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions C++/sum-of-subarray-minimums.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Time: O(n)
// Space: O(n)

// Ascending stack solution
class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
static const int M = 1e9 + 7;

vector<int> left(A.size());
stack<pair<int, int>> s1;
for (int i = 0; i < A.size(); ++i) {
int count = 1;
while (!s1.empty() && s1.top().first > A[i]) {
count += s1.top().second;
s1.pop();
}
s1.emplace(A[i], count);
left[i] = count;
}

vector<int> right(A.size());
stack<pair<int, int>> s2;
for (int i = A.size() - 1; i >= 0; --i) {
int count = 1;
while (!s2.empty() && s2.top().first >= A[i]) {
count += s2.top().second;
s2.pop();
}
s2.emplace(A[i], count);
right[i] = count;
}

int result = 0;
for (int i = 0; i < A.size(); ++i) {
result = (result + A[i] * left[i] * right[i]) % M;
}
return result;
}
};

0 comments on commit 6ca484e

Please sign in to comment.