084 Largest Rectangle In Histogram
这道题有两个做法 总体来说都是O(n) 但是第二个方法是第一个的简化版
方法一:
l[i] = max(j) 其中a[j], a[j+1], ...,a[i-1] < a[i]
r[i] = min(j) 其中 a[i] > a[i+1], ... ,a[j]
dif[i] = r[i] - l[i]
area[i] = a[i] * dif[i]
最大的area[i] 即为答案
a[i] : -inf, 2, 3, 1, 4, 6, 5, 7, 3, 2, -inf
i : 0, 1 ,2, 3, 4, 5, 6, 7, 8, 9, 10
l[i] : , 0, 1, 0, 3, 4, 4, 6, 3, 3,
r[i] : , 3, 3,10, 8, 6, 8,8, 9,10
dif[i]: , 3, 2, 10, 5, 2, 4, 2, 6, 7
area[i]: ,4, 3, 9, 16, 6, 15, 7, 15, 12
方法二:
是第一种方法的改良, 使用stack, 在stack中记录a[i] 及 l[i]
具体代码如下
1 class Solution: 2 # @param {integer[]} height 3 # @return {integer} 4 def largestRectangleArea(self, height): 5 ans = 0 6 s = [] 7 for i in range(0, len(height)): 8 left = i 9 while (s != []) and (s[-1][0] > height[i]): 10 left = s[-1][1] 11 ans = max(ans, (i - left) * s[-1][0]) 12 s.pop() 13 s.append([height[i], left]) 14 right = len(height) 15 while s != []: 16 left = s[-1][1] 17 ans = max(ans, (right - left) * s[-1][0]) 18 s.pop() 19 return ans