150 XP

99. Largest rectangle in a histogram

Expert stacks

A histogram is a row of bars, each 1 unit wide, standing side by side; heights[i] is the height of bar i. A rectangle drawn under the histogram must sit on the ground, cover one or more whole bars next to each other, and be no taller than the shortest bar it covers.

Write a function largest_rectangle(heights) that returns the largest area such a rectangle can have. With no bars, the answer is 0.

Trying every pair of edges is slow. Instead, ask for each bar: how far left and right can a rectangle of exactly its height stretch? A stack of bars whose heights rise from bottom to top answers that for every bar in one pass.

Example 1

Inputheights = [3, 1, 3, 2, 2]
Output6
ExplanationHeight 2 over the last three bars: 2 * 3.

Example 2

Inputheights = [4, 4, 4]
Output12
ExplanationAll three bars, 4 high: 4 * 3.

Example 3

Inputheights = []
Output0
ExplanationNo bars, no rectangle.

Constraints

  • heights has 0 to 1000 whole numbers, each from 0 to 10^4.

Submit also runs 10 more tests you can't see.

Code
def largest_rectangle(heights):
    """Find the largest rectangle under a histogram.

    heights: list of int, the bars' heights, side by side
    Returns: int, the largest area of a rectangle under
        the bars
    """
    # Write your code here
    pass