一. Largest Rectangle in Histogram
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.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
Difficulty:Hard
TIME:TIMEOUT
解法
這道題如果採用
假設是一個增序列比如<1,2,3,4,5>,由於右邊的數都要比左邊大,因此如果以左邊的數作爲邊是完全可行的。但我們知道左邊的下標,但還是不確定右邊的下標,因爲沒有出現一個小於棧頂的數。如果序列變成了<1,2,3,4,5,3>,這個時候就開始計算最大值了,從5開始,到4:
- 對於5來說,長方形面積爲5 * 1 = 5
- 對於4來說,長方形面積爲4 * 2 = 8
序列這個時候變成了<1,2,3,3>,也就是說比3大的數都計算完成。繼續添加其餘的數。
int largestRectangleArea(vector<int>& heights) {
if(heights.empty())
return 0;
heights.push_back(0); //後導0用來清空棧
int result = 0;
vector<int> v;
for(int i = 0; i < heights.size(); i++) {
while(!v.empty() && heights[i] < heights[v.back()]) {
int h = heights[v.back()];
v.pop_back();
int k = v.empty() ? -1 : v.back(); //注意這裏是用前一個數的下標來計算的
result = max((i - k - 1) * h, result); //計算面積
}
v.push_back(i);
}
return result;
}
代碼的時間複雜度爲