Problem:
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.
Above is a histogram the where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, and which has an area = 10
unit.
For example,
Given height = [2,1,5,6,2,3]
,
Return 10
.
Hide TagsArray StackTest instructions: Looking for the largest rectangular area in an array-represented bar chart
Thinking:
(1) First think of brute force, two traversal, record the maximum area. The commit discovery timed out.
(2) http://blog.csdn.net/doc_sgl/article/details/11805519 presents an O (n) algorithm implemented with a stack, which is efficient.
The general idea is that thestack contains only the height of the monotonically increasing index, the largest rectangle is most likely to appear in these columns
Code
Brute force: Submit to TLE
Class Solution {public: int Largestrectanglearea (vector<int> &height) { int n=height.size (); if (n==0) return 0; if (n<2) return height[0]; int area=height[0]; int index=0; for (int i=1;i<n;i++) { index=height[i]; for (int j=i;j>=0;j--) { index=min (index,height[j]); Area=max (area,index* (i-j+1)); } } return area; }};
With the stack O (N) algorithm
Class Solution {public: int Max (int a, int b) {return a > b a:b;} int Largestrectanglearea (vector<int> &height) { height.push_back (0); stack<int> Stk; int i = 0; int maxarea = 0; while (I < height.size ()) { if (stk.empty () | | height[stk.top ()] <= height[i]) { stk.push (i++); } else { int t = stk.top (); Stk.pop (); Maxarea = Max (Maxarea, Height[t] * (Stk.empty ()? I:i-Stk.top ()-1)); } } return maxarea;} ;
Leetcode | | 84, largest Rectangle in histogram