LeetCode – Largest Rectangle in Histogram (Java)
Given n nonnegative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example, given height = [2,1,5,6,2,3], return 10.
Analysis
The key to solve this problem is to maintain a stack to store bars' indexes. The stack only keeps the increasing bars.
Java Solution
public int largestRectangleArea(int[] height) { if (height == null  height.length == 0) { return 0; } Stack<Integer> stack = new Stack<Integer>(); int max = 0; int i = 0; while (i < height.length) { //push index to stack when the current height is larger than the previous one if (stack.isEmpty()  height[i] >= height[stack.peek()]) { stack.push(i); i++; } else { //calculate max value when the current height is less than the previous one int p = stack.pop(); int h = height[p]; int w = stack.isEmpty() ? i : i  stack.peek()  1; max = Math.max(h * w, max); } } while (!stack.isEmpty()) { int p = stack.pop(); int h = height[p]; int w = stack.isEmpty() ? i : i  stack.peek()  1; max = Math.max(h * w, max); } return max; } 
<pre><code> String foo = "bar"; </code></pre>

Alok

Rohit Kaushik

roboto120

Jon Bramley

AJ

Anusha

Shariq Aziz

Elvira Gandelman

Snail914

Thompson Hu

jason zhang

Jason Zhu

Jason Zhu

aegis

Satish