GivenNNon-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.
The data (INDEX) in the stack is sorted in ascending order. When the number is smaller than the previous number, the calculation starts and the number pop of the stack is larger than the current element.
84. largest rectangle in Histogram