Largest Rectangle in Histogram
ID: 122; hard
Solution 1 (Java)
public class Solution {
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
public int largestRectangleArea(int[] height) {
if (height == null || height.length == 0)
return 0;
int maxArea = 0;
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i <= height.length; i++) {
int curr = i == height.length ? -1 : height[i];
while (!stack.isEmpty() && curr <= height[stack.peek()]) {
int target = stack.pop();
int h = height[target];
int w = stack.isEmpty() ? i : i - stack.peek() - 1;
maxArea = Math.max(maxArea, h * w);
}
stack.push(i);
}
return maxArea;
}
}
// |
// | |
// | |
// | | |
// | | | | |
// | | | | | |
// i = 6: cur = -1; target = 1, h = 1, w = 6, ans = 10
// stack = []Notes
Last updated