forked from Haresh1204/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRectangle.java
More file actions
31 lines (24 loc) · 827 Bytes
/
LargestRectangle.java
File metadata and controls
31 lines (24 loc) · 827 Bytes
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
import java.util.Stack;
public class LargestRectangle {
public static void main(String[] args) {
int[] arr = {2,1,5,6,2,3};
int res = largestRectangleArea(arr);
System.out.println(res);
}
public static int largestRectangleArea(int[] heights) {
int len = heights.length;
Stack<Integer> s = new Stack<>();
int maxArea = 0;
for (int i = 0; i <= len; i++){
int h = (i == len ? 0 : heights[i]);
if (s.isEmpty() || h >= heights[s.peek()]) {
s.push(i);
} else {
int top = s.pop();
maxArea = Math.max(maxArea, heights[top] * (s.isEmpty() ? i : i - 1 - s.peek()));
i--;
}
}
return maxArea;
}
}