-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestRectangle.java
More file actions
38 lines (31 loc) · 1.24 KB
/
largestRectangle.java
File metadata and controls
38 lines (31 loc) · 1.24 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
/*
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
For example, Given height = [2,1,5,6,2,3], return 10.
Solution: O(n)
Reference: http://www.cnblogs.com/lichen782/p/leetcode_Largest_Rectangle_in_Histogram.html
Another solution: O(nlogn), using Divide and Conquer.
Find the smallest histogram first. So the largest histogram is the height of smallest histogram * total length, or on the left or on the right. Do this process recursively.
*/
public class Solution {
public int largestRectangleArea(int[] height) {
if(height == null || height.length==0){
return 0;
}
int[] h = new int[height.length + 1];
h = Arrays.copyOf(height, height.length + 1);
//height[height.length+1]=0;
Stack<Integer> st = new Stack<Integer>();
int r=0;
int max=0;
while(r<h.length){
if(st.isEmpty() || h[st.peek()] <= h[r]){
st.push(r++);
}else{
int t = st.pop();
int len = st.isEmpty() ? r : r - st.peek() - 1;
max = Math.max(max, h[t] * len);
}
}
return max;
}
}