地址:http://oj.leetcode.com/problems/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 height = [2,1,5,6,2,3]
,
return 10
.
参考代码:
class Solution:
# @param height, a list of integer
# @return an integer
def largestRectangleArea(self, height):
if not height: return 0
elif len(height)==1:return height[0]
i = 0
ans = 0
flag = False
while i < len(height) and not flag:
while i<len(height)-1 and height[i] <= height[i+1]:
i += 1
if i == len(height)-1:
flag = True
min_height = height[i]
for j in range(i, -1, -1):
min_height = min(min_height, height[j])
ans = max(ans, min_height*(i-j+1))
i+=1
return ans
思路:
上面python用的是分治法,可以ac,但是c++可能时间卡的比较严格,会tle
用stack来解,如果栈为空或者当前读入的数值不小于栈顶的值,将该值入栈,并读入下一个值。
否则(当前读入的值小于栈顶最小值),把小于当前值的栈内所有值都pop出来,并算出此时面积。
算面积时考虑两种情况,一个是栈已空,一个是栈非空。
如此,直到遍历完(读入)所有值。
若此时栈非空,栈里的数值一定是非降序的,同样考虑栈空和非空两种情况,算出面积。
最后的结果是上述面积值的最大值。
参考代码:
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
if(height.empty())
return 0;
stack<int>st;
int pos, ans = 0;
for(int i = 0; i<height.size(); ++i) {
while(!st.empty() && height[i] < height[st.top()]) {
pos = st.top();
st.pop();
ans = max(ans, height[pos] * (st.empty() ? i : i-st.top()-1));
}
st.push(i);
}
while(!st.empty()){
pos = st.top();
st.pop();
ans = max(ans, height[pos] * (int)(st.empty() ? height.size() : height.size()-1-st.top()));
}
return ans;
}
};