Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
sum-of-subarray-minimums.cpp 1.04 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-09-16 19:30 +08:00 . Create sum-of-subarray-minimums.cpp
// Time: O(n)
// Space: O(n)
// Ascending stack solution
class Solution {
public:
int sumSubarrayMins(vector<int>& A) {
static const int M = 1e9 + 7;
vector<int> left(A.size());
stack<pair<int, int>> s1;
for (int i = 0; i < A.size(); ++i) {
int count = 1;
while (!s1.empty() && s1.top().first > A[i]) {
count += s1.top().second;
s1.pop();
}
s1.emplace(A[i], count);
left[i] = count;
}
vector<int> right(A.size());
stack<pair<int, int>> s2;
for (int i = A.size() - 1; i >= 0; --i) {
int count = 1;
while (!s2.empty() && s2.top().first >= A[i]) {
count += s2.top().second;
s2.pop();
}
s2.emplace(A[i], count);
right[i] = count;
}
int result = 0;
for (int i = 0; i < A.size(); ++i) {
result = (result + A[i] * left[i] * right[i]) % M;
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助