算法分析课每周练习 Largest Rectangle in Histogram

来源:互联网 发布:美工常用72种字体打包 编辑:程序博客网 时间:2024/06/08 17:14

题目

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.

分析

比较容易想到O(n^2)级的算法,但这题其实有更优秀的方法

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
这题与室友找工作时见到的一条面试题源出一脉,居然是用stack实现的算法。