cpp: add “907. Sum of Subarray Minimums”
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
48eae7f00b
commit
0505779f3f
1 changed files with 31 additions and 0 deletions
31
cpp/sum-of-subarray-minimums.cpp
Normal file
31
cpp/sum-of-subarray-minimums.cpp
Normal 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);
|
||||||
|
}
|
||||||
|
};
|
Loading…
Reference in a new issue