Mural on the Stepped Wall

Hardmonotonic stackAlso known as Largest Rectangle in Histogram

A school courtyard has an old garden wall built from columns of bricks, each column one brick wide, standing side by side with no gaps between them. Over the years some columns lost bricks, so the top of the wall is a jagged staircase. A column with height 0 has lost all its bricks.

The art class wants to paint the biggest possible rectangular mural on the wall. The rectangle must sit on the ground, cover whole columns side by side, and stay on bricks: it cannot rise above the shortest column it spans.

Your task

Write largestMural(heights). heights[i] is the number of bricks in column i, and each brick is 1 × 1. Return the largest area, in bricks, of a rectangle that spans one or more consecutive columns and is no taller than the shortest of them.

Return 0 for an empty wall or a wall with no bricks at all.

largestMural(heights: int[]) → int

Examples

Example 1
Input
heights = [3, 5, 4, 1, 6, 2]
Output
9
Why

Columns 0 to 2 (heights 3, 5, 4) are all at least 3 tall, giving 3 × 3 = 9. The tallest column alone gives only 6, and columns 1 and 2 give 4 × 2 = 8. Any rectangle that includes column 3 is at most 1 brick tall: 1 × 6 = 6.

Example 2
Input
heights = [2, 4, 4, 0, 5]
Output
8
Why

Columns 1 and 2 give 4 × 2 = 8. Column 3 has no bricks, so no rectangle can cross it, and the 5 on its own is only 5.

Constraints

  • 0 ≤ heights.length ≤ 100,000
  • 0 ≤ heights[i] ≤ 10,000
Start with brute force

Try every pair of start and end columns, keep a running minimum height as the end moves right, and compute minimum × width.

That is O(n²): about 5 billion pairs for a wall of 100,000 columns. Most of the work is wasted because a run of columns is rechecked from every starting point. The insight is that each column only needs to know where it is blocked on each side.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code