[leetcode]Largest Rectangle in Histogram @ Python

时间:2022-01-17 21:00:45

原题地址:https://oj.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.

[leetcode]Largest Rectangle in Histogram @ Python

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

[leetcode]Largest Rectangle in Histogram @ Python

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,
Given height = [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.

(Note: it is better use another different example to walk through the steps, and you will understand it better).
[leetcode]Largest Rectangle in Histogram @ Python

代码:

class Solution:
# @param height, a list of integer
# @return an integer
# @good solution!
def largestRectangleArea(self, height):
maxArea = 0
stackHeight = []
stackIndex = []
for i in range(len(height)):
if stackHeight == [] or height[i] > stackHeight[len(stackHeight)-1]:
stackHeight.append(height[i]); stackIndex.append(i)
elif height[i] < stackHeight[len(stackHeight)-1]:
lastIndex = 0
while stackHeight and height[i] < stackHeight[len(stackHeight)-1]:
lastIndex = stackIndex.pop()
tempArea = stackHeight.pop() * (i-lastIndex)
if maxArea < tempArea: maxArea = tempArea
stackHeight.append(height[i]); stackIndex.append(lastIndex)
while stackHeight:
tempArea = stackHeight.pop() * (len(height) - stackIndex.pop())
if tempArea > maxArea:
maxArea = tempArea
return maxArea

代码:

class Solution:
# @param height, a list of integer
# @return an integer
# @good solution!
def largestRectangleArea(self, height):
stack=[]; i=0; area=0
while i<len(height):
if stack==[] or height[i]>height[stack[len(stack)-1]]:
stack.append(i)
else:
curr=stack.pop()
width=i if stack==[] else i-stack[len(stack)-1]-1
area=max(area,width*height[curr])
i-=1
i+=1
while stack!=[]:
curr=stack.pop()
width=i if stack==[] else len(height)-stack[len(stack)-1]-1
area=max(area,width*height[curr])
return area

常规解法,所有的面积都算一遍,时间复杂度O(N^2)。不过会TLE。

代码:

class Solution:
# @param height, a list of integer
# @return an integer
# @good solution!
def largestRectangleArea(self, height):
maxarea=0
for i in range(len(height)):
min = height[i]
for j in range(i, len(height)):
if height[j] < min: min = height[j]
if min*(j-i+1) > maxarea: maxarea = min*(j-i+1)
return maxarea