-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathSum of Subarray Ranges.java
68 lines (63 loc) · 2.18 KB
/
Sum of Subarray Ranges.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Solution {
class Node{
long val, displace;
Node(long val, long displace){
this.val = val;
this.displace = displace;
}
}
public long subArrayRanges(int[] nums) {
//lesser than current element
Stack<Node> stack = new Stack<>();
//from left
long [] lesserLeft = new long[nums.length];
for (int i = 0; i< nums.length; i++){
long count = 1;
while(stack.size()>0 && stack.peek().val<=nums[i]){
count+=stack.pop().displace;
}
stack.add(new Node(nums[i], count));
lesserLeft[i] = count;
}
stack.clear();
//from right
long[] lesserRight = new long[nums.length];
for (int i = nums.length-1; i>=0; i--){
long count = 1;
while(stack.size()>0 && stack.peek().val<nums[i]){
count+=stack.pop().displace;
}
stack.add(new Node(nums[i], count));
lesserRight[i] = count;
}
//greater than current element
stack.clear();
//from left
long [] greaterLeft = new long[nums.length];
for (int i = 0; i< nums.length; i++){
long count = 1;
while(stack.size()>0 && stack.peek().val>=nums[i]){
count+=stack.pop().displace;
}
stack.add(new Node(nums[i], count));
greaterLeft[i] = count;
}
stack.clear();
//from right
long[] greaterRight = new long[nums.length];
for (int i = nums.length-1; i>=0; i--){
long count = 1;
while(stack.size()>0 && stack.peek().val>nums[i]){
count+=stack.pop().displace;
}
stack.add(new Node(nums[i], count));
greaterRight[i] = count;
}
long ans = 0;
//Now we subtract the count of minimum occurrences from the count of maximum occurrences
for (int i = 0; i< nums.length; i++){
ans+=((lesserLeft[i]*lesserRight[i]) - (greaterLeft[i]*greaterRight[i]))*nums[i];
}
return ans;
}
}