Practice · Monotonic stack · 2 of 2

Largest Rectangle Under a Bar Chart

You are given heights, the heights of the bars in a bar chart, from left to right. Every bar is 1 unit wide, and the bars stand side by side with no gaps.

Return the area of the largest rectangle that fits entirely inside the chart: its bottom on the baseline, its sides on bar edges, and its top no higher than any bar it covers.

Example 1

Input
heights = [2, 4, 5, 3, 1, 3]
Output
9
A rectangle 3 high spans the bars 4, 5 and 3: 3 × 3 = 9.

Example 2

Input
heights = [6, 2]
Output
6
The tall bar alone (6 × 1) beats the short one stretched across both (2 × 2).

Constraints

  • heights holds 1 to 10⁵ bars.
  • Every height is between 0 and 10⁴.