您的位置:首页 > 编程语言 > Python开发

[leetcode]@python 84. Largest Rectangle in Histogram

2016-02-03 13:56 736 查看

题目链接

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: