mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
31 lines
766 B
C++
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);
|
|
}
|
|
};
|