-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 118.java
More file actions
48 lines (38 loc) · 1.44 KB
/
Day 118.java
File metadata and controls
48 lines (38 loc) · 1.44 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
int subarrayRanges(vector<int>& arr) {
int n = arr.size();
vector<int> leftGreater(n), rightGreater(n);
vector<int> leftSmaller(n), rightSmaller(n);
stack<int> st;
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.top()] <= arr[i]) st.pop();
leftGreater[i] = st.empty() ? i + 1 : i - st.top();
st.push(i);
}
while (!st.empty()) st.pop();
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && arr[st.top()] < arr[i]) st.pop();
rightGreater[i] = st.empty() ? n - i : st.top() - i;
st.push(i);
}
while (!st.empty()) st.pop();
for (int i = 0; i < n; i++) {
while (!st.empty() && arr[st.top()] >= arr[i]) st.pop();
leftSmaller[i] = st.empty() ? i + 1 : i - st.top();
st.push(i);
}
while (!st.empty()) st.pop();
for (int i = n - 1; i >= 0; i--) {
while (!st.empty() && arr[st.top()] > arr[i]) st.pop();
rightSmaller[i] = st.empty() ? n - i : st.top() - i;
st.push(i);
}
long long maxSum = 0, minSum = 0;
for (int i = 0; i < n; i++) {
maxSum += (long long)arr[i] * leftGreater[i] * rightGreater[i];
minSum += (long long)arr[i] * leftSmaller[i] * rightSmaller[i];
}
return (int)(maxSum - minSum);
}
};