Largest Rectangle in Histogram
1 approach, code in every language
Problem description
You are given an array `heights` where each entry is the height of a bar in a histogram and every bar has width `1`.
Consider any rectangle whose top edge is flat and that fits entirely under the histogram outline, spanning one or more contiguous bars. The height of such a rectangle is limited by the shortest bar it covers, and its width is the number of consecutive bars it spans.
Return the area of the largest rectangle that can be formed within the histogram.
Example 1
Input: heights = [2,1,5,6,2,3]
Output: 10
The bars of height 5 and 6 form a rectangle of height 5 and width 2, giving area 10, which is the maximum.
Example 2
Input: heights = [2,4]
Output: 4
The single bar of height 4 gives area 4, beating the width-2 rectangle of height 2 (area 4 as well but not larger).
Constraints
1 <= heights.length <= 10^50 <= heights[i] <= 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Largest Cut from a Slate Wall is our own problem on the technique behind Largest Rectangle in Histogram: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free