From 0505779f3f8b51a0b781494c8244a4b5fb3036e9 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 20 Jan 2024 23:16:24 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=E2=80=9C907.=20Sum=20of=20Subarra?= =?UTF-8?q?y=20Minimums=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/sum-of-subarray-minimums.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 cpp/sum-of-subarray-minimums.cpp diff --git a/cpp/sum-of-subarray-minimums.cpp b/cpp/sum-of-subarray-minimums.cpp new file mode 100644 index 0000000..28ca0fb --- /dev/null +++ b/cpp/sum-of-subarray-minimums.cpp @@ -0,0 +1,31 @@ +#include + +class Solution { + static const int MOD = 1000000007; + + public: + int sumSubarrayMins(const std::vector &arr) { + long s = 0; + + std::vector stack; + for (auto i = 0; i <= static_cast(arr.size()); ++i) { + while (!stack.empty() && + (i == arr.size() || arr[stack.back()] >= arr[i])) { + int mid = stack.back(); + stack.pop_back(); + + int l = stack.empty() ? -1 : stack.back(); + int r = i; + + long count = (mid - l) * (r - mid) % MOD; + + s += (count * arr[mid]) % MOD; + s %= MOD; + } + + stack.push_back(i); + } + + return static_cast(s); + } +};