leetcode84. Largest Rectangle in Histogram

topic:

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

 

Violence ideas:

Through each column, it is to seek maximum height of the rectangular area (looking left and right of the first smaller than its pillars, called the left border and right border ). Finally get global maximum area. The time complexity of O (N ^ 2)

Improve:

This is a trick question type of problem, I personally feel little significance

1, with a stack, followed by the column index pushed, when the top of the stack to be pressed into the column above the column, we can find, we found a stack pillars of the right border . We'll post the stack pop, denoted by x, and started looking for its left edge.

2, since the press-fit strategy above, the stack height of the column must be <= height x. Continue to pop the top element (these columns == height x height) until the column height of the top of the stack <height x. Then we find the x's left border . X can be calculated as the maximum height of the rectangular area.

3, then we have a new top of the stack, so they took the new top of the stack and to push the pillar to pillar than ... repeat the above action until the top of the stack columns <= to push pillars

The map will draw a very intuitive, but I will not draw, you can see leetcode resolution

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        blocks = [0]
        maxArea = 0
        heights.append(0)
        for i in range(1,len(heights)):
            while len(blocks)>0 and heights[blocks[-1]] > heights[i]:
                right = i-1
                h = heights[blocks.pop()]
                while len(blocks)>0 and heights[blocks[-1]] == h:
                    blocks.pop()
                if len(blocks)>0:
                    left = blocks[-1]
                else:
                    left = -1
                maxArea = max(maxArea, h*(right-left))
            blocks.append(i)
        return maxArea

 

 

 

Published 82 original articles · won praise 2 · Views 4340

Guess you like

Origin blog.csdn.net/qq_22498427/article/details/105091562