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
这道题目推荐看官方解答,非常详细:Largest Rectangle In Histogram - LeetCode Articles
其中最巧妙的解法是使用栈,空间的复杂度是O(N),时间的复杂度据官方说法也是O(N),我不是很清楚,有知道的人可以告诉我一声。
java解法:
public class Solution {
public int largestRectangleArea(int[] heights) {
Stack < Integer > stack = new Stack < > ();
stack.push(-1);
int maxarea = 0;
for (int i = 0; i < heights.length; ++i) {
while (stack.peek() != -1 && heights[stack.peek()] >= heights[i])
maxarea = Math.max(maxarea, heights[stack.pop()] * (i - stack.peek() - 1));
stack.push(i);
}
while (stack.peek() != -1)
maxarea = Math.max(maxarea, heights[stack.pop()] * (heights.length - stack.peek() -1));
return maxarea;
}
}
c++解法:
class Solution {
public:
int largestRectangleArea(vector<int>& A) {
int n = A.size(), ans = 0, pos = 0;
stack<int> st;
for (int i = 0; i <= n; i++) {
while (!st.empty() && (i == n || A[st.top()] >= A[i])) {
pos = st.top(); st.pop();
ans = max(ans, A[pos] * (st.empty() ? i : i-st.top()-1));
}
st.push(i);
}
return ans;
}
};
Python解法:
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
heights.append(0)
stack = [-1]
ans = 0
for i in range(len(heights)):
while heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - stack[-1] - 1
ans = max(ans, h * w)
stack.append(i)
heights.pop()
return ans