Largest Rectangle in a Histogram
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A histogram consists of N bars of width 1 standing side by side on the ground; bar i has height heights[i]. Return
the largest area of an axis-aligned rectangle that lies entirely inside the histogram with its bottom on the ground —
that is, the maximum of (r - l + 1) × min(heights[l..r]) over all ranges [l, r].
Examples
| heights | result |
|---|---|
[2, 1, 5, 6, 2, 3] | 10 |
[2, 4] | 4 |
[3, 3, 3, 0, 1] | 9 |
Example 1 — Height 5 across the bars of height 5 and 6 gives area 10.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(heights: int[]) → long
Constraints
-
heights.length -
heights[i] - The answer may exceed 32 bits.
Expected complexity
- Time
- O(N)
- Space
- O(N)
Examples
| heights | Expected |
|---|---|
[2,1,5,6,2,3] | 10 |
[2,4] | 4 |
[3,3,3,0,1] | 9 |
Hint
Hint
The best rectangle's height equals some bar's height, and that rectangle extends until the first strictly lower bar on each side. A stack of increasing heights finds both boundaries: when the current bar is not higher than the stack top, pop it — its right boundary is the current index and its left boundary is the new stack top. Append a height-0 sentinel to flush the stack. Use 64-bit areas. Expanding around every bar is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1082 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |