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.
For example, given height = [2,1,5,6,2,3].
The largest rectangle area is 10 unit.
Thinking
基本思想:用栈维护一个递增子序列
为了方便记录矩形的宽度,我们在栈中存放的是矩形的下标。
我们用 i 遍历所有的矩形,当栈尾元素 j 对应的矩形高度大于或等于当前遍历到的矩形时(出现了局部非递增),可以保证:__前面出现的上升序列中可能存在最大面积__。如下图:
这样当遇到局部递减时,依次取出栈尾,如果 s 未空面积 area = height[cur] * (i-s.top()-1) 就是栈尾元素对应的高度乘以跨度,如果此时s已空, area = height[cur] * i。
classSolution { public: /** * @param height: A list of integer * @return: The area of largest rectangle in the histogram */ intlargestRectangleArea(vector<int> &height){ int result = 0; height.push_back(0); stack<int> s; for (int i = 0; i < height.size(); ++i) { while (!s.empty() && height[s.top()] >= height[i]) { int cur = s.top(), area; s.pop(); if (s.empty()) area = height[cur] * i; else area = height[cur] * (i-s.top()-1); result = max(result, area); } s.push(i); } return result; } };