84. Largest Rectangle in Histogram
Last updated
Last updated
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.Input: heights = [2,4]
Output: 4func largestRectangleArea(heights []int) int {
ans, monoStack := 0, make([]int, 0, len(heights)) // stores indices
heights = append(append([]int{0}, heights...), 0)
for i := 0; i < len(heights); i++ {
for len(monoStack) > 0 && heights[i] < heights[monoStack[len(monoStack)-1]] {
curHeight := heights[monoStack[len(monoStack)-1]]
monoStack = monoStack[:len(monoStack)-1]
width := i - monoStack[len(monoStack)-1] - 1
if s := width * curHeight; s > ans {
ans = s
}
}
monoStack = append(monoStack, i)
}
return ans
}