From 6ca484e8f086f5afda6cebbea1fa7557260c5392 Mon Sep 17 00:00:00 2001 From: kamyu Date: Sun, 16 Sep 2018 19:30:19 +0800 Subject: [PATCH] Create sum-of-subarray-minimums.cpp --- C++/sum-of-subarray-minimums.cpp | 40 ++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C++/sum-of-subarray-minimums.cpp diff --git a/C++/sum-of-subarray-minimums.cpp b/C++/sum-of-subarray-minimums.cpp new file mode 100644 index 000000000..76e6b6b48 --- /dev/null +++ b/C++/sum-of-subarray-minimums.cpp @@ -0,0 +1,40 @@ +// Time: O(n) +// Space: O(n) + +// Ascending stack solution +class Solution { +public: + int sumSubarrayMins(vector& A) { + static const int M = 1e9 + 7; + + vector left(A.size()); + stack> 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 right(A.size()); + stack> 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; + } +};