The Expected "Largest Rectangle" in this histogram is in shaded area which equals 10 unit.

As I stated at the beginning, there's O(n) solution for this problem by taking advantage of stacks. I'm not going to the details of that algorithm, assuming we now have a function

int findMax(int[] heights)

which can get the max rectangle area in the histogram in O(n) time, then we can easily solve the Maximal Rectangle Problem.How?

We need to construct an assistant matrix to help usrecord the "histogram" of each row. As shown in the red rectangle, the corresponding row in the assistant matrix is the histogram of that row in the original matrix.Then we just need to process the input matrix row by row, and for each row, we use findMax function to calculate the largest rectangle area:

heights.push(height[i]); indices.push(lastIndex); } //note:if current = top , just ignore it. } /** * note: after processing, there still maybe elements in the stack. * but they MUST BE in ascending order in the stack from bottom to top. */ while(!heights.empty()){ int temp = (height.length-indices.pop())*heights.pop(); if(temp>max) max = temp; } return max;

}That's pretty much my general idea. In order to make it more efficient, we can merge findMax function into our maximalRectangle(). Therefore we don't need to create new stacks by scanning each row. And we don't need to traversal each row twice either.