Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
heights = [2,1,5,6,2,3]10heights = [2,4]4heights = [1,1,1,1,1]5maxArea = 0. Iterate i from 0 to n (sentinel h=0 at i=n)i, get h = (i==n) ? 0 : heights[i]h < heights[stack.top]: pop and compute areawidth = stack.empty ? i : i−stack.top−1, update maxi onto stack. Continue until all bars processed.maxAreaWe maintain a monotonically increasing stack of bar indices. When a shorter bar arrives, every taller bar behind it can no longer extend rightward — so we pop each and compute the maximum rectangle it could form. The width is determined by the gap between the current index and the new stack top (left boundary). The sentinel h=0 at position n flushes all remaining bars at the end.
Trying every pair of left and right edges is O(n²). For each bar, we really want how far it can stretch left and right while staying the shortest.
Keep a stack of bar indexes with increasing heights. When a shorter bar arrives, the taller bars on the stack cannot stretch any further right. So pop them one by one: each popped bar is the height, and the width runs from the new top of the stack to the current index. A zero-height bar at the end flushes everything left on the stack.
Pop a bar when a shorter one arrives; that is when its width is known. Width runs from the new stack top to the current index.
Run the animation above on your own input, or watch the 1:40 video explanation of Largest Rectangle in Histogram with a dry run and Java code.