Skip to content
BytePatterns

Largest Bar Rectangle

HardStacks & Queues#monotonic-stack~45m

Problem

A bar chart is described by a list of heights, where every bar has width one and they stand side by side with no gaps. Find the area of the largest rectangle that fits entirely inside the bars. The rectangle may span several neighbouring bars, but its height can never exceed the shortest bar it covers.

Examples

Input:  heights = [2, 1, 5, 6, 2, 3]
Output: 10
Why:    the bars of height 5 and 6 support a rectangle two wide and five tall
Input:  heights = [2, 4]
Output: 4
Why:    one tall bar beats the two-wide rectangle of height two
Input:  heights = []
Output: 0
Why:    edge case, an empty chart holds no rectangle

Hints

0 / 3

Stuck on the idea rather than the code? Largest Rectangle covers it.