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
Solution 1: Monotonic Stack
Use a monotonic stack to maintain the higher bars’s indices in ascending order.
When encounter a lower bar, pop the tallest bar and use it as the bottleneck to compute the area.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua, 12ms, 10.7MB class Solution { public: int largestRectangleArea(vector<int>& heights) { heights.push_back(0); const int n = heights.size(); stack<int> s; int ans = 0; int i = 0; while (i < n) { if (s.empty() || heights[i] >= heights[s.top()]) { s.push(i++); } else { int h = heights[s.top()]; s.pop(); int w = s.empty() ? i : i - s.top() - 1; ans = max(ans, h * w); } } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment