-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRectangleInHistogram.java
More file actions
37 lines (33 loc) · 1 KB
/
LargestRectangleInHistogram.java
File metadata and controls
37 lines (33 loc) · 1 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
class Solution {
class Node {
private int index; // min index can cover
private int value;
public Node(int index, int value) {
this.index = index;
this.value = value;
}
}
public int largestRectangleArea(int[] h) {
int m = h.length;
Stack<Node> st = new Stack<>();
int result = 0;
for (int j = 0; j < m; j++) {
int index = j;
while (!st.isEmpty() && st.peek().value >= h[j]) {
Node node = st.pop();
int area = (j - node.index) * node.value;
result = Math.max(result, area);
index = node.index;
}
if (h[j] > 0) {
st.add(new Node(index, h[j]));
}
}
while (!st.isEmpty()) {
Node node = st.pop();
int area = (m - node.index) * node.value;
result = Math.max(result, area);
}
return result;
}
}