zoukankan      html  css  js  c++  java
  • [leetcode]@python 84. Largest Rectangle in Histogram

    题目链接

    https://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 heights = [2,1,5,6,2,3],
    return 10.

    题目大意

    给定一个包含小矩形高度的数组,返回这些小矩形覆盖区域的最大矩形的面积

    解题思路

    Actually, we can decrease the complexity by using stack to keep track of the height and start indexes. Compare the current height with previous one.
    Case 1: current > previous (top of height stack)
    Push current height and index as candidate rectangle start position.
    Case 2: current = previous
    Ignore.
    Case 3: current < previous
    Need keep popping out previous heights, and compute the candidate rectangle with height and width (current index - previous index). Push the height and index to stacks.

    http://www.cnblogs.com/zuoyuan/p/3783993.html

    代码

    class Solution(object):
        def largestRectangleArea(self, heights):
            """
            :type heights: List[int]
            :rtype: int
            """
            stack = []
            i = 0
            area = 0
    
            while i < len(heights):
                if stack == [] or heights[i] > heights[stack[len(stack) - 1]]:
                    stack.append(i)
                else:
                    cur = stack.pop()
                    if stack == []:
                        width = i
                    else:
                        width = i - stack[len(stack) - 1] - 1
                    area = max(area, width * heights[cur])
                    i -= 1
                i += 1
    
            while stack != []:
                cur = stack.pop()
                if stack == []:
                    width = i
                else:
                    width = len(heights) - stack[len(stack) - 1] - 1
                area = max(area, width * heights[cur])
    
            return area
    
  • 相关阅读:
    bzoj4821
    bzoj2434
    第二阶段团队项目冲刺站立会议(五)
    第二阶段团队项目冲刺站立会议(四)
    第二阶段团队项目冲刺站立会议(三)
    小水王
    第二阶段团队项目冲刺站立会议(二)
    梦断代码阅读笔记02
    第二阶段团队项目冲刺站立会议(一)
    梦断代码阅读笔记01
  • 原文地址:https://www.cnblogs.com/slurm/p/5179546.html
Copyright © 2011-2022 走看看