← All coding problems
Largest Rectangle in Histogram
hardStack & Queue+40 XPTime limit 2s
A histogram has n bars of width 1 and heights h[i]. Find the area of the largest rectangle that fits entirely inside the histogram.
Input:
- line 1:
n - line 2:
nheights
Output: the largest area (it can need a 64-bit integer).
Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ h[i] ≤ 10⁴.
Think about it: for each bar, the best rectangle using that bar's full height stretches left and right until a shorter bar. A monotonic increasing stack finds both boundaries for every bar in one O(n) pass.
Sample input 1
6 2 1 5 6 2 3
Sample output 1
10
Sample input 2
2 2 4
Sample output 2
4
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).