Problem 130
Largest Rectangle in Histogram
Hard · 30 pts · Array, Stack, Monotonic Stack
Problem
A histogram has N bars of width 1 standing side by side, and bar i has height H[i]. Find the area of the largest rectangle that fits entirely inside the histogram. A rectangle spanning several neighbouring bars can be at most as tall as the shortest of them. For each bar, the best rectangle of its height extends left and right until it meets a shorter bar. A monotonic stack finds these boundaries for every bar in a single O(N) pass.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the maximum area.
Constraints
1 <= N <= 100000; 0 <= H[i] <= 10000
Example input
6 2 1 5 6 2 3
Example output
10
Explanation
In 2 1 5 6 2 3, the neighbouring bars of height 5 and 6 can hold a rectangle of height 5 and width 2, with area 5 × 2 = 10. No other rectangle is larger, so the answer is 10.