-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
66 lines (58 loc) · 1.78 KB
/
Copy pathsolution.cpp
File metadata and controls
66 lines (58 loc) · 1.78 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class Solution
{
public:
int subarrayRanges(vector<int> &arr)
{
int n = arr.size();
long long maxSum = 0, minSum = 0;
vector<int> left(n), right(n);
stack<int> st;
// ---------- Maximum Contribution ----------
// Previous Greater
while (!st.empty())
st.pop();
for (int i = 0; i < n; i++)
{
while (!st.empty() && arr[st.top()] <= arr[i])
st.pop();
left[i] = st.empty() ? i + 1 : i - st.top();
st.push(i);
}
// Next Greater
while (!st.empty())
st.pop();
for (int i = n - 1; i >= 0; i--)
{
while (!st.empty() && arr[st.top()] < arr[i])
st.pop();
right[i] = st.empty() ? n - i : st.top() - i;
st.push(i);
}
for (int i = 0; i < n; i++)
maxSum += (long long)arr[i] * left[i] * right[i];
// ---------- Minimum Contribution ----------
while (!st.empty())
st.pop();
// Previous Smaller
for (int i = 0; i < n; i++)
{
while (!st.empty() && arr[st.top()] >= arr[i])
st.pop();
left[i] = st.empty() ? i + 1 : i - st.top();
st.push(i);
}
// Next Smaller
while (!st.empty())
st.pop();
for (int i = n - 1; i >= 0; i--)
{
while (!st.empty() && arr[st.top()] > arr[i])
st.pop();
right[i] = st.empty() ? n - i : st.top() - i;
st.push(i);
}
for (int i = 0; i < n; i++)
minSum += (long long)arr[i] * left[i] * right[i];
return maxSum - minSum;
}
};