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 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.
简单解法:对于每一个height[i],寻找以此height[i]作为长方形的宽,然后寻找此长方形的最左边和最右边。8 milli secs过小数据,大数据超时
class Solution { public: int largestRectangleArea(vector<int> &height) { // Start typing your C/C++ solution below // DO NOT write int main() function int len = height.size(); if(len < 1) return 0; int left, right ,i, maxArea = 0; for(i = 0; i< len ; i++) { int currentHeight = height[i] ; if(currentHeight == 0 ) continue; left = i; while(left >= 0 && height[left] >= currentHeight) { left --; } left++; right = i; while(right < len && height[right] >= currentHeight) { right++; } right--; int area = currentHeight *(right - left + 1) ; maxArea = maxArea < area ? area : maxArea ; } return maxArea ; } };
对上一个算法做出改进:用一个栈来优化对每个height[i]左右边界的寻找,从左到右扫描数组,如果当前栈S为空,则把当前的i值放入栈中;或者如果当前节点的高度大于栈顶节点的高度,也把当前的i值压入栈中(注意这里的不断压栈其实在寻找栈顶节点的矩形的右边界)。当当前节点的高度小于于当前栈顶节点的高度时,此节点便是当前栈中所有节点高度值大于该值的长方形的右边界;剩下的任务就是寻找左边界,栈中每个节点的左边界其实是其栈中的上一个元素。
这样对于数组中每个元素最多进一次栈,出一次栈。所以时间复杂度为O(n)
class Solution { public: int largestRectangleArea(vector<int> &height) { // Start typing your C/C++ solution below // DO NOT write int main() function int len = height.size(); if(len < 1) return 0; stack<int> myS ; int area ,i, tp, maxArea = 0; for(i = 0; i< len ;) { int currentHeight = height[i] ; if(myS.empty() || currentHeight >= height[myS.top()] ) { myS.push(i); i++; }else{ tp = myS.top(); myS.pop(); area = height[tp] *(myS.empty() ? i : i - myS.top() -1 ) ; maxArea = maxArea < area ? area : maxArea ; } } while(!myS.empty()) { tp = myS.top(); myS.pop(); area = height[tp] *( myS.empty() ? i : i - myS.top() -1 ) ; maxArea = maxArea < area ? area : maxArea ; } return maxArea ; } };
[ reference]: http://www.geeksforgeeks.org/largest-rectangle-under-histogram/