-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathSumOfSubarrayRanges.java
52 lines (44 loc) · 1.7 KB
/
SumOfSubarrayRanges.java
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
package com.dbc;
import java.util.Stack;
public class SumOfSubarrayRanges {
public long subArrayRanges(int[] nums) {
int[] minLeft = new int[nums.length];
int[] maxLeft = new int[nums.length];
int[] minRight = new int[nums.length];
int[] maxRight = new int[nums.length];
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
for (int i = 0; i < nums.length; i++) {
while (!stack1.isEmpty() && nums[stack1.peek()] > nums[i]) {
stack1.pop();
}
minLeft[i] = stack1.isEmpty() ? -1 : stack1.peek();
stack1.push(i);
while (!stack2.isEmpty() && nums[stack2.peek()] < nums[i]) {
stack2.pop();
}
maxLeft[i] = stack2.isEmpty() ? -1 : stack2.peek();
stack2.push(i);
}
stack1 = new Stack<>();
stack2 = new Stack<>();
for (int i = nums.length - 1; i >= 0; i--) {
while (!stack1.isEmpty() && nums[stack1.peek()] >= nums[i]) {
stack1.pop();
}
minRight[i] = stack1.isEmpty() ? nums.length : stack1.peek();
stack1.push(i);
while (!stack2.isEmpty() && nums[stack2.peek()] <= nums[i]) {
stack2.pop();
}
maxRight[i] = stack2.isEmpty() ? nums.length : stack2.peek();
stack2.push(i);
}
long minSum = 0, maxSum = 0;
for (int i = 0; i < nums.length; i++) {
minSum += (long) (i - minLeft[i]) * (minRight[i] - i) * nums[i];
maxSum += (long) (i - maxLeft[i]) * (maxRight[i] - i) * nums[i];
}
return maxSum - minSum;
}
}