99. Largest rectangle in a histogram
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
heights = [3, 1, 3, 2, 2]6Example 2
heights = [4, 4, 4]12Example 3
heights = []0Constraints
heightshas 0 to 1000 whole numbers, each from 0 to 10^4.
Submit also runs 10 more tests you can't see.
- Keep a stack of bar indexes whose heights rise from the bottom of the stack to the top. When a bar comes that is not taller than the top one, the top bar's rectangle can't stretch any further right.
- Pop it: its rectangle reaches right to just before the new bar, and left to just after the bar now below it on the stack (or to the start, if the stack is empty). Its area is its height times that width.
- Add a bar of height 0 at the end, so every bar left on the stack gets popped and measured too.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.