forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum-of-subarray-ranges.cpp
30 lines (29 loc) · 1.04 KB
/
sum-of-subarray-ranges.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Time: O(n)
// Space: O(n)
class Solution {
public:
long long subArrayRanges(vector<int>& nums) {
int64_t result = 0;
vector<int> stk;
for (int i = 0; i <= size(nums); ++i) {
const int x = (i < size(nums)) ? nums[i] : numeric_limits<int>::max();
while (!empty(stk) && nums[stk.back()] <= x) {
const int64_t j = stk.back(); stk.pop_back();
const int64_t k = !empty(stk) ? stk.back() : -1;
result += nums[j] * (j - k) * (i - j);
}
stk.emplace_back(i);
}
stk.clear();
for (int i = 0; i <= size(nums); ++i) {
const int x = (i < size(nums)) ? nums[i] : numeric_limits<int>::min();
while (!empty(stk) && nums[stk.back()] >= x) {
const int64_t j = stk.back(); stk.pop_back();
const int64_t k = !empty(stk) ? stk.back() : -1;
result -= nums[j] * (j - k) * (i - j);
}
stk.emplace_back(i);
}
return result;
}
};