Largest Rectangle in a Skyline

HardStack≈ 50 min

A skyline is made of buildings standing side by side, each one unit wide; their heights are given in the list heights, from left to right. Return the area of the largest rectangle that fits inside the skyline: its bottom on the ground, and every part of it inside some building.

Examples

text
heights = [2, 1, 5, 6, 2, 3]      →  10
heights = [2, 4]                  →  4
heights = [3, 3, 3]               →  9
heights = [6, 2, 5, 4, 5, 1, 6]   →  12

In the first example the buildings of height 5 and 6 hold a rectangle 5 high and 2 wide. In the last, the four buildings 2, 5, 4, 5 hold one 2 high and 4 wide, but the three 5, 4, 5 hold one 4 high and 3 wide: 12.

Constraints

  • Between 0 and 20,000 buildings, each between 0 and 10,000 high.
  • Aim for O(n): every building should be put on, and taken off, a stack once.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 10 on the judge, 6 of them hidden, and measures how your solution scales.