Largest rectangle in a histogram
Find the biggest rectangle that fits under a histogram, using a monotonic stack of bar indices to size each bar's full width in one pass.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
A bar can only stretch as a rectangle until it meets a shorter bar on either side. Walking left to right with a stack of increasing heights, a shorter bar forces every taller bar still on the stack to finally know its right edge, and the stack itself gives its left edge. A sentinel zero-height bar at the very end flushes out whatever remains.
Code
public static int LargestRectangleArea(int[] heights) {
var stack = new Stack<int>(); // indices, heights increasing
int best = 0;
for (int i = 0; i <= heights.Length; i++) {
int h = i == heights.Length ? 0 : heights[i];
while (stack.Count > 0 && heights[stack.Peek()] >= h) {
int top = stack.Pop();
int width = stack.Count == 0 ? i : i - stack.Peek() - 1;
best = Math.Max(best, heights[top] * width);
}
stack.Push(i);
}
return best;
}static int largestRectangleArea(int[] heights) {
Deque<Integer> stack = new ArrayDeque<>(); // indices, heights increasing
int best = 0;
for (int i = 0; i <= heights.length; i++) {
int h = i == heights.length ? 0 : heights[i];
while (!stack.isEmpty() && heights[stack.peek()] >= h) {
int top = stack.pop();
int width = stack.isEmpty() ? i : i - stack.peek() - 1;
best = Math.max(best, heights[top] * width);
}
stack.push(i);
}
return best;
}int largestRectangleArea(const vector<int>& heights) {
stack<int> st; // indices, heights increasing
int best = 0, n = (int)heights.size();
for (int i = 0; i <= n; i++) {
int h = i == n ? 0 : heights[i];
while (!st.empty() && heights[st.top()] >= h) {
int top = st.top(); st.pop();
int width = st.empty() ? i : i - st.top() - 1;
best = max(best, heights[top] * width);
}
st.push(i);
}
return best;
}def largest_rectangle_area(heights: list[int]) -> int:
stack = [] # indices, heights increasing
best = 0
for i in range(len(heights) + 1):
h = 0 if i == len(heights) else heights[i]
while stack and heights[stack[-1]] >= h:
top = stack.pop()
width = i if not stack else i - stack[-1] - 1
best = max(best, heights[top] * width)
stack.append(i)
return bestTips
- The width of a popped bar is the gap between the new stack top and the current index, minus one.
- This is the same "pop until smaller" shape as next greater element, just using the gap between indices instead of a value.
In the .NET library
Without the sentinel pass at i == heights.Length, bars still on the stack when the array ends would never get measured. Pushing one extra height-0 bar handles that cleanly.