-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay 166.java
More file actions
49 lines (37 loc) · 1.16 KB
/
Day 166.java
File metadata and controls
49 lines (37 loc) · 1.16 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
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> stack = new Stack<>();
for (int i = 0; i < n; i++) {
while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) {
stack.pop();
}
if (stack.isEmpty()) {
left[i] = i + 1;
} else {
left[i] = i - stack.peek();
}
stack.push(i);
}
stack.clear();
for (int i = n - 1; i >= 0; i--) {
while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) {
stack.pop();
}
if (stack.isEmpty()) {
right[i] = n - i;
} else {
right[i] = stack.peek() - i;
}
stack.push(i);
}
long sum = 0;
for (int i = 0; i < n; i++) {
sum += (long) arr[i] * left[i] * right[i];
}
return (int) sum;
}
}