-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path022. SumOfSubarrayRanges.java
More file actions
70 lines (60 loc) · 2.02 KB
/
022. SumOfSubarrayRanges.java
File metadata and controls
70 lines (60 loc) · 2.02 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
67
68
69
70
class Solution {
public int subarrayRanges(int[] arr) {
int n = arr.length;
long maxSum = sumSubarrayMax(arr, n);
long minSum = sumSubarrayMin(arr, n);
return (int)(maxSum - minSum);
}
private long sumSubarrayMax(int[] arr, int n) {
long sum = 0;
int[] left = new int[n];
int[] right = new int[n];
java.util.Stack<Integer> stack = new java.util.Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] <= arr[i]) {
stack.pop();
}
left[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] < arr[i]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n - i : stack.peek() - i;
stack.push(i);
}
for (int i = 0; i < n; i++) {
sum += (long) arr[i] * left[i] * right[i];
}
return sum;
}
private long sumSubarrayMin(int[] arr, int n) {
long sum = 0;
int[] left = new int[n];
int[] right = new int[n];
java.util.Stack<Integer> stack = new java.util.Stack<>();
// Previous smaller element
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.pop();
}
left[i] = stack.isEmpty() ? i + 1 : i - stack.peek();
stack.push(i);
}
stack.clear();
// Next smaller or equal element
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
stack.pop();
}
right[i] = stack.isEmpty() ? n - i : stack.peek() - i;
stack.push(i);
}
for (int i = 0; i < n; i++) {
sum += (long) arr[i] * left[i] * right[i];
}
return sum;
}
}