Largest rectangle in a histogram
A histogram is a bar chart. This one has bars of width 1 standing side by side with no gaps, and heights[i] is the height of bar i. You want to draw a rectangle inside the chart. It stands on the ground, covers a run of neighboring bars, and is no taller than the shortest bar in that run.
Return the largest area such a rectangle can have, as an integer.
heights = [2, 4, 5, 1, 3]Output8Cover the bars of height 4 and 5. The shorter one is 4, so the rectangle is 4 tall and 2 wide: 4 × 2 = 8.
heights = [2, 1, 2]Output3Each 2 alone gives an area of 2. The 1 is short, but a rectangle 1 tall can cover all three bars, for an area of 3.
heights = [3, 3, 3]Output9One rectangle 3 tall covers all three bars: 3 × 3 = 9.
1 ≤ len(heights) ≤ 105
0 ≤ heights[i] ≤ 104
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.