-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
51 lines (44 loc) · 1.54 KB
/
Copy pathsolution.java
File metadata and controls
51 lines (44 loc) · 1.54 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
class Solution {
public int subarrayRanges(int[] arr) {
int n = arr.length;
long maxSum = 0, minSum = 0;
int[] left = new int[n];
int[] right = new int[n];
Stack<Integer> st = new Stack<>();
// ---------- Maximum ----------
st.clear();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] <= arr[i])
st.pop();
left[i] = st.isEmpty() ? i + 1 : i - st.peek();
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] < arr[i])
st.pop();
right[i] = st.isEmpty() ? n - i : st.peek() - i;
st.push(i);
}
for (int i = 0; i < n; i++)
maxSum += (long) arr[i] * left[i] * right[i];
// ---------- Minimum ----------
st.clear();
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] >= arr[i])
st.pop();
left[i] = st.isEmpty() ? i + 1 : i - st.peek();
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] > arr[i])
st.pop();
right[i] = st.isEmpty() ? n - i : st.peek() - i;
st.push(i);
}
for (int i = 0; i < n; i++)
minSum += (long) arr[i] * left[i] * right[i];
return (int) (maxSum - minSum);
}
}