awelgorithms

Histogram largest rectangle

Updated

For each bar i, nearest strictly smaller to the left (L) and to the right (R) bound the widest rectangle of height a[i]. Width = R - L - 1 with sentinels L = -1 and R = n. Area = a[i] * width. The answer is the max area.

What to focus on

Two monotonic passes (or one pass with leftover pops at a virtual 0-height bar) give every L and R in O(n). Do not try every (L, R) pair in O(n²).

Worked examples

three bars

a = [4, 1, 9]
  1. i=0: L=-1 R=1 width 1 area 4
  2. i=1: L=-1 R=3 width 3 area 3
  3. i=2: L=1 R=3 width 1 area 9

Result: max 9

four bars

a = [4, 1, 9, 1]
  1. i=0 area 4
  2. i=1 width 4 area 4
  3. i=2 area 9
  4. i=3 width 4 area 4

Result: max 9

one bar

a = [4]
  1. L=-1 R=1 width 1
  2. area 4

Result: max 4

Try it

Write largestRectangle(a). a is the list of bar heights. Return the maximum rectangle area. Width comes from next-smaller left and right sentinels: width = R - L - 1. [4, 1, 9] → 9. [4, 1, 9, 1] → 9. [2, 1, 2] → 3 (the middle 1 spans width 3).

a is a non-empty list of positive bar heights.