-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
48 lines (35 loc) · 1.06 KB
/
Copy pathsolution.java
File metadata and controls
48 lines (35 loc) · 1.06 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
import java.util.*;
class Solution {
public int sumSubMins(int[] arr) {
int n = arr.length;
int[] left = new int[n];
int[] right = new int[n];
Stack<Integer> st = new Stack<>();
// Previous Less Element
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && arr[st.peek()] > arr[i])
st.pop();
if (st.isEmpty())
left[i] = i + 1;
else
left[i] = i - st.peek();
st.push(i);
}
st.clear();
// Next Less Element
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && arr[st.peek()] >= arr[i])
st.pop();
if (st.isEmpty())
right[i] = n - i;
else
right[i] = st.peek() - i;
st.push(i);
}
long ans = 0;
for (int i = 0; i < n; i++) {
ans += (long) arr[i] * left[i] * right[i];
}
return (int) ans;
}
}