Given bar heights of a histogram where each bar has width 1, return the area of the largest rectangle that fits inside it.
Keep indices of increasing heights on a stack. When a shorter bar arrives, every taller bar on the stack has found its right edge; its left edge is the index below it on the stack. Pop and measure.
1function largestRectangleArea(heights: number[]): number {2const stack: number[] = []; let best = 0;3for (let i = 0; i <= heights.length; i++) {4const h = i === heights.length ? 0 : heights[i];5while (stack.length && heights[stack.at(-1)!] > h) {6const top = stack.pop()!;7const left = stack.length ? stack.at(-1)! + 1 : 0;8best = Math.max(best, heights[top] * (i - left));9}10stack.push(i);11}12return best;13}
Empty stack.
Space: play/pause · ←/→: step