Largest rectangle in a histogram

A histogram is a row of bars of width 1 with the given heights. Find the area of the largest rectangle that fits inside it.

What to build

A program that finds the largest rectangle area in a histogram.

Requirements

  • The rectangle must sit on the baseline and be made of whole consecutive bars; its height is the shortest bar it covers.
  • Use a monotonic stack for O(n) time.

Input

The first line has n. The second line has the n bar heights.

Output

The largest area.

Constraints

1 ≤ n ≤ 10⁵; heights from 0 to 10⁴.

Example

Input:

6
2 1 5 6 2 3

Output:

10

Why it works

The best rectangle with a given bar as its shortest bar reaches left and right until a shorter bar. A stack of increasing heights finds both limits: when a shorter bar arrives, each taller bar it pops has its right limit there and its left limit just below it on the stack.

Examples

Example 1 · Input
6
2 1 5 6 2 3
Expected output
10
Example 2 · Input
2
2 4
Expected output
4

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

A bar can extend left and right until it meets a shorter bar. Find those two limits for every bar.

Hint 2

Keep a stack of bar positions with increasing heights. A shorter bar pops taller ones and finishes their rectangles.

Hint 3

Add a bar of height 0 at the end so every bar gets popped.

Solution

Show one correct solution (try it yourself first)
n = int(input())
h = list(map(int, input().split())) + [0]
stack = []
best = 0
for i, height in enumerate(h):
    start = i
    while stack and stack[-1][1] >= height:
        pos, top = stack.pop()
        best = max(best, top * (i - pos))
        start = pos
    stack.append((start, height))
print(best)

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Stacks and queues →