【LeetCode】84. Largest Rectangle in Histogram(C++)
阿新 • • 發佈:2019-01-01
地址:https://leetcode.com/problems/largest-rectangle-in-histogram/
題目:
Given
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
理解:
給了一個柱狀圖,要求其能構成的矩形的最大面積。構成的矩形不能超過其起始任意一個矩形的高。也就是說,矩形的高是受限於高度最矮的矩形的。
覺得這個題和Container With Most Water
實現:
參考:Largest Rectangular Area in a Histogram
藉助了一個棧,儲存比當前矮的位置。i為工作指標
如果heights[i]大於等於棧頂,就把其入棧;
如果小於,則依次彈出棧頂,並用彈出的值當作當前矩形的高,i-1為矩形的右邊界,而把新的棧頂+1作為左邊界。如果棧為空,就說明沒有更矮的了,直接把0作為左邊界就可以了。
class Solution {
public:
int largestRectangleArea(vector< int>& heights) {
int maxArea = 0;
stack<int> stk;
for (int i = 0; i <= heights.size(); i++) {
int h = (i == heights.size() ? 0 : heights[i]);
if (stk.empty() || h >= heights[stk.top()])
stk.push(i);
else {
int heightIndex = stk.top();
stk.pop();
int r = i - 1;
int l = stk.empty() ? 0 : stk.top()+1;
int width = r - l + 1;
maxArea = max(maxArea, heights[heightIndex] * width);
i--;
}
}
return maxArea;
}
};