Largest Rectangle in Histogram

Hard

heights[i] is the height of a bar of width 1. Return the area of the largest rectangle that fits inside the histogram.

Example 1

largestRectangleArea()
Input
heights = [2,1,5,6,2,3]
Output
10

Why

The 5×2 rectangle spanning bars 2 and 3.

Example 2

largestRectangleArea()
Input
heights = [2,4]
Output
4
Constraints
1 <= heights.length <= 10^5
0 <= heights[i] <= 10^4

Topics

ArraysStackMonotonic Stack

Implement largestRectangleArea in the editor and return the answer — printing it is never graded.