Skip to main content
←Architecture WorkspaceArchOSWorkspaces/
Sign in
ALGORITHM CANVAS · MONOTONIC INCREASING STACK · TIME O(N) · SPACE O(N)
Largest Rectangle in Histogram
Maintain bars in increasing height order. When a shorter bar arrives, popped bars know BOTH their exact left and right limiting walls.
STACK CHAIN (1 NODES)0HEAD
STEP 1/5 · L9
heights=[2,1,5,6,2,3]i=0stack=[0]best=0
PYTHON 3.12 · INSTANT PREVIEW
1def largest_rect(heights):
2 stack = []
3 best = 0
4 for i, h in enumerate(heights + [0]):
5 while stack and heights[stack[-1]] > h:
6 ht = heights[stack.pop()]
7 w = i if not stack else i - stack[-1] - 1
8 best = max(best, ht * w)
9 stack.append(i)
10 return best