-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2104.java
More file actions
59 lines (58 loc) · 1.61 KB
/
2104.java
File metadata and controls
59 lines (58 loc) · 1.61 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
class Solution {
public long subArrayRanges(int[] nums) {
int n=nums.length;
long s_os=0,s_ol=0;
Stack<Integer> st=new Stack<>();
int pse[]=new int[n];
int nse[]=new int[n];
int ple[]=new int[n];
int nle[]=new int[n];
int mod=1000000007;
for(int i=0;i<n;i++){
while(!st.isEmpty() && nums[st.peek()]>=nums[i]){
st.pop();
}
pse[i]=(st.isEmpty())?-1:st.peek();
st.push(i);
}
while(!st.isEmpty()){
st.pop();
}
for(int i=0;i<n;i++){
while(!st.isEmpty() && nums[st.peek()]<=nums[i]){
st.pop();
}
ple[i]=(st.isEmpty())?-1:st.peek();
st.push(i);
}
while(!st.isEmpty()){
st.pop();
}
for(int i=n-1;i>=0;i--){
while(!st.isEmpty() && nums[st.peek()]>nums[i]){
st.pop();
}
nse[i]=(st.isEmpty())?n:st.peek();
st.push(i);
}
while(!st.isEmpty()){
st.pop();
}
for(int i=n-1;i>=0;i--){
while(!st.isEmpty() && nums[st.peek()]<nums[i]){
st.pop();
}
nle[i]=(st.isEmpty())?n:st.peek();
st.push(i);
}
for(int i=0;i<n;i++){
long right_s=nse[i]-i;
long left_s=i-pse[i];
long right_l=nle[i]-i;
long left_l=i-ple[i];
s_os+=(right_s*left_s*nums[i]);
s_ol+=(right_l*left_l*nums[i]);
}
return s_ol-s_os;
}
}