Mural on the Stepped Wall

Hardmonotonic stackAlso known as Largest Rectangle in Histogram

A school courtyard's old garden wall is built from columns of bricks, each one brick wide, side by side with no gaps. Some columns have lost bricks, so the top is a jagged staircase; a column of height 0 has none left.

The art class wants the biggest rectangular mural possible. It must sit on the ground, cover whole adjacent columns, and stay on bricks: no taller than the shortest column it spans.

Your task

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

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

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, so they give 3 × 3 = 9. The tallest column alone gives 6, columns 1 and 2 give 4 × 2 = 8, and any rectangle that includes column 3 is at most 1 tall, so it gives at most 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 column of height 5 alone gives 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 100,000 columns, rechecking the same runs from every start. 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