LeetCode Largest Rectangle in Histogram
Largest Rectangle in Histogram
Original question
Given a bar chart, find the maximum area of the rectangle that it can contain. For example, the shadow part is the required rectangle.
Note:
The width of all columns is 1.
Example:
Input: heights = [2, 1, 5, 6, 2, 3]
Output: 10
Solutions
This question has been stuck for a long time and I have never imagined a good solution. After checking some information, the elegant method is to solve the problem through stack.
First, it is clear that the final height of the rectangle must be the height of a column. The above example may be one of, and, and try to expand to both sides to get the maximum area, the time complexity is too large. Think about the reason for trying to expand to both sides, for example, the second 2 in the example (if it is high, it can cover a maximum of four columns ), because its left and right sides of adjacent columns have higher than it, that is to say, the height of the column is not orderly. If we can get an orderly ascending arrangement, we just need to expand like the right, do not expand to the left, because the column on the left is lower than itself.
Traverse the columnar structure in sequence. If it is incremental, press the stack. If it is not, the columns higher than it will pop up in sequence (only the columns higher than the current column will pop up to ensure that the current column is pressed after the stack, the column in the stack continues to increase sequentially), and calculates the area of the rectangle with the column as the height. When calculating the area, the width should be the width between the top element of the stack and the traversal element. For example, when the second 2 is displayed, there is no element smaller than 2, to enable the element to pop up smoothly, add a value of 0 at the end of the original bar chart. The top element of the stack is 1, so that the width of the stack can be calculated as 4. Another problem is that the stack has no elements and the width cannot be calculated when the value of 1 is displayed. Therefore, a-1 value must be added at the bottom of the stack during initialization to cope with the situation where all elements exit the stack.
AC Source Code
class Solution(object): def largestRectangleArea(self, heights): """ :type heights: List[int] :rtype: int """ heights.append(0) stack = [-1] result = 0 for i in range(len(heights)): while heights[i] < heights[stack[-1]]: h = heights[stack.pop()] w = i - stack[-1] - 1 result = max(result, h * w) stack.append(i) heights.pop() return resultif __name__ == "__main__": assert Solution().largestRectangleArea([2, 1, 5, 6, 2, 3]) == 10