forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
32 lines (31 loc) · 992 Bytes
/
Solution2.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
31
32
class Solution {
public:
long long subArrayRanges(vector<int>& nums) {
long long mx = f(nums);
for (int i = 0; i < nums.size(); ++i) nums[i] *= -1;
long long mi = f(nums);
return mx + mi;
}
long long f(vector<int>& nums) {
stack<int> stk;
int n = nums.size();
vector<int> left(n, -1);
vector<int> right(n, n);
for (int i = 0; i < n; ++i) {
while (!stk.empty() && nums[stk.top()] <= nums[i]) stk.pop();
if (!stk.empty()) left[i] = stk.top();
stk.push(i);
}
stk = stack<int>();
for (int i = n - 1; i >= 0; --i) {
while (!stk.empty() && nums[stk.top()] < nums[i]) stk.pop();
if (!stk.empty()) right[i] = stk.top();
stk.push(i);
}
long long ans = 0;
for (int i = 0; i < n; ++i) {
ans += (long long) (i - left[i]) * (right[i] - i) * nums[i];
}
return ans;
}
};