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.
class Solution {
public int largestRectangleArea(int[] heights) {
int n = heights.length;
if(n < 1) {
return 0;
}
Stack<Integer> stacks = new Stack<Integer>();
int[] h = new int[n + 1];
h = Arrays.copyOf(heights, n + 1);
int i = 0;
int area = 0;
while(i < h.length) {
if(stacks.isEmpty() || h[stacks.peek()] <= h[i]) {
stacks.push(i++);
} else {
int t = stacks.pop();
area = Math.max(area, h[t]*(stacks.isEmpty() ? i : i - stacks.peek() - 1));
}
}
return area;
}
}