Skip to the code
cf.
+50 XP

#268 Biggest Rectangle Under a Bar Chart

hard

A chart library wants to place a text label inside a bar chart where it has the most room. The bars are side by side, each 1 unit wide, and heights[i] is the height of bar i.

Write largestArea(heights) that returns the area of the largest rectangle that fits completely inside the bars. The rectangle must sit on the baseline and cover a run of neighboring bars, and its height can't be more than the shortest bar it covers.

Example 1

Input: heights = [3,1,4,6,5,2]
Output: 12

Bars 4, 6, and 5 hold a rectangle of height 4 and width 3, area 12.

Example 2

Input: heights = [2,4]
Output: 4

Either the single bar 4, or both bars at height 2: area 4.

Constraints

  • 1 <= heights.length <= 10^5
  • 0 <= heights[i] <= 10^4
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).