1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00
LeetCode/cpp/sum-of-subarray-minimums.cpp
Matej Focko 0505779f3f
cpp: add “907. Sum of Subarray Minimums”
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-01-20 23:16:24 +01:00

31 lines
766 B
C++

#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);
}
};