5
Node(long val, long displace) {7
this.displace = displace;11
public long subArrayRanges(int[] nums) {13
// lesser than current element14
Stack<Node> stack = new Stack<>();16
long[] lesserLeft = new long[nums.length];17
for (int i = 0; i < nums.length; i++) {19
while (stack.size() > 0 && stack.peek().val <= nums[i]) {20
count += stack.pop().displace;22
stack.add(new Node(nums[i], count));23
lesserLeft[i] = count;27
long[] lesserRight = new long[nums.length];28
for (int i = nums.length - 1; i >= 0; i--) {30
while (stack.size() > 0 && stack.peek().val < nums[i]) {31
count += stack.pop().displace;33
stack.add(new Node(nums[i], count));34
lesserRight[i] = count;37
// greater than current element40
long[] greaterLeft = new long[nums.length];41
for (int i = 0; i < nums.length; i++) {43
while (stack.size() > 0 && stack.peek().val >= nums[i]) {44
count += stack.pop().displace;46
stack.add(new Node(nums[i], count));47
greaterLeft[i] = count;51
long[] greaterRight = new long[nums.length];52
for (int i = nums.length - 1; i >= 0; i--) {54
while (stack.size() > 0 && stack.peek().val > nums[i]) {55
count += stack.pop().displace;57
stack.add(new Node(nums[i], count));58
greaterRight[i] = count;62
// Now we subtract the count of minimum occurrences from the count of maximum occurrences64
for (int i = 0; i < nums.length; i++) {65
ans += ((lesserLeft[i] * lesserRight[i]) - (greaterLeft[i] * greaterRight[i])) * nums[i];