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.
Example:
Input: [2,1,5,6,2,3] Output: 10
my code:(very inefficient)
class Solution { public: int largestRectangleArea(vector<int>& heights) { int len = heights.size(); int res = 0; for (int i = 0; i < len; ++i) { int nums = 1; for (int j = i+1; j < len; ++j) { if (heights[j] >= heights[i]) nums++; else break; } for (int k = i-1; k >= 0; --k) { if (heights[k] >= heights[i]) nums++; else break; } res = max(res, heights[i]*nums); } return res; } };
Runtime: 1664 ms, faster than 1.28% of C++ online submissions for Largest Rectangle in Histogram.
height efficient code:
class Solution { public: int largestRectangleArea(vector<int>& heights) { int len = heights.size(); int res = 0; stack<int> s; heights.push_back(0); for (int i = 0; i <= len; ++i) { int h = i==len ? 0 : heights[i]; while (!s.empty() && h < heights[s.top()]) { int height = heights[s.top()]; s.pop(); int start = s.empty() ? -1 : s.top(); int nums = i - start - 1; res = max(res, height*nums); } s.push(i); } return res; } };
Runtime: 12 ms, faster than 45.96% of C++ online submissions for Largest Rectangle in Histogram.
stack中的数据(索引)升序进行排列,遇到小于前面的数开始计算,并将stack中比当前元素大的数pop。