PracticeNeetCode ↗LeetCode ↗
Given an array heights representing a histogram's bar heights, where each bar has width 1, return the area of the largest rectangle that fits entirely within the histogram.
(start_index, height) pairs) and set max_area to 0.i, height h: while the stack's top has a height greater than h, pop it, compute its area as height * (i - start_index), update max_area, and remember its start_index as the new bar's own start.(start, h) onto the stack.len(heights) as the right boundary), updating max_area each time.Time: O(n) — Space: O(n)
def largestRectangleArea(heights: list[int]) -> int:
stack = [] # (start_index, height) pairs
max_area = 0
for i, h in enumerate(heights):
start = i
while stack and stack[-1][1] > h:
index, height = stack.pop()
max_area = max(max_area, height * (i - index))
start = index
stack.append((start, h))
for index, height in stack:
max_area = max(max_area, height * (len(heights) - index))
return max_areaHow the solution above works, piece by piece.
(start_index, height) pairs with heights increasing from bottom to top.h is lower than the top, the top bar's rectangle can't extend past i. Pop it and measure height * (i - index).start = index: the new, shorter bar can extend left to where the popped bar began, so it's pushed with that earlier start.len(heights) - index.Running it on heights = [2, 1, 5, 6, 2, 3]: