LeetCodeDifficult- [84. The largest rectangle in the histogram]

Given  n  non-negative integers, it is used to represent the height of each column in the histogram. Each pillar is adjacent to each other and has a width of 1.

Find the maximum area of ​​the rectangle that can be outlined in this histogram.

The above is an example of a histogram, where each column has a width of 1 and a given height is  [2,1,5,6,2,3].

Example:

Input: [2,1,5,6,2,3]
 Output: 10

Idea: Stack (Sentinel Skill)

Detailed explanation: https://leetcode-cn.com/problems/largest-rectangle-in-histogram/solution/bao-li-jie-fa-zhan-by-liweiwei1419/

simple description:

Use a stack to store the index of each column, traverse the heights array, if the current height is greater than or equal to the previous height, the index will be added to the stack, otherwise you need to meet the heights [i] <heights [stack [- The elements of 1]] are pushed out of the stack in sequence, and the largest rectangle they can form is calculated.

important point:

1. You need to add a 0 before and after the original array, so that there must be a smaller value than the elements of the height array.

2. Each time the stack is popped first, then the subscript of the top element of the stack is read, and the width of the current rectangle is calculated.

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        max_area = 0
        heights = [0] + heights + [0]
        stack = []
        for i in range(len(heights)):
            while len(stack) > 0 and heights[i] < heights[stack[-1]]:
                top = stack.pop() # 需要提前弹出!!!
                max_area = max(max_area, heights[top] * (i - stack[-1] - 1))
            stack.append(i)
        return max_area

 

Published 314 original articles · 22 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/qq_39451578/article/details/105052846