-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_84_largest_histogram.java
More file actions
39 lines (38 loc) · 1.36 KB
/
Copy path_84_largest_histogram.java
File metadata and controls
39 lines (38 loc) · 1.36 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
import java.util.ArrayDeque;
import java.util.Deque;
public class _84_largest_histogram {
public int largestRectangleArea(int[] heights) {
int maxArea = 0;
int current =0;
Deque<Integer> stack = new ArrayDeque<>();
while(current<heights.length){
if(stack.isEmpty() || heights[current] >= heights[stack.peek()]){
stack.push(current);
current++;
}else{
while(!stack.isEmpty()&&heights[current] < heights[stack.peek()]){
int heightIndex = stack.pop();
int width;
if(!stack.isEmpty()){
width = current - stack.peek() - 1;
}else{
width = current;
}
maxArea = Math.max((heights[heightIndex]*width), maxArea);
}
}
}
while(!stack.isEmpty()){
int heightIndex = stack.pop();
int width;
current = heights.length;
if(!stack.isEmpty()){
width = current - stack.peek() - 1;
}else{
width = current;
}
maxArea = Math.max((heights[heightIndex]*width), maxArea);
}
return maxArea;
}
}