Funcia
Lv.3arraymonotonic-stackstack

Largest Rectangle in a Histogram

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
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

heightsresult
[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

  • 1≤N=1 \le N = heights.length ≤500,000\le 500{,}000
  • 0≤0 \le heights[i] ≤109\le 10^9
  • The answer may exceed 32 bits.

Expected complexity

Time
O(N)
Space
O(N)

Examples

heightsExpected
[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 O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251082 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness4011verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.