-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0084.py
44 lines (36 loc) · 1.4 KB
/
0084.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Source: https://leetcode.com/problems/largest-rectangle-in-histogram
# Title: Largest Rectangle in Histogram
# Difficulty: Hard
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# 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.
#
# Example:
#
# Input: [2,1,5,6,2,3]
# Output: 10
#
################################################################################################################################
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
n = len(heights)
left_index = [0]*n
right_index = [n]*n
# Find right index
stack = []
for i in range(n):
while stack and heights[stack[-1]] > heights[i]:
right_index[stack.pop()] = i
stack.append(i)
# Find left index
stack = []
for i in range(n-1, -1, -1):
while stack and heights[stack[-1]] > heights[i]:
left_index[stack.pop()] = i+1
stack.append(i)
# Compute area
ans = 0
for i, height in enumerate(heights):
area = height * (right_index[i] - left_index[i])
ans = max(ans, area)
return ans