1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00

cpp: add “907. Sum of Subarray Minimums”

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-01-20 23:16:24 +01:00
parent 48eae7f00b
commit 0505779f3f
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,31 @@
#include <vector>
class Solution {
static const int MOD = 1000000007;
public:
int sumSubarrayMins(const std::vector<int> &arr) {
long s = 0;
std::vector<int> stack;
for (auto i = 0; i <= static_cast<int>(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<int>(s);
}
};