84. Largest Rectangle in Histogram

Description

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.

Example 1:

Example 2:

Constraints:

  • 1 <= heights.length <= 10^5

  • 0 <= heights[i] <= 10^4

Tags

Array, Stack

Solution

We use a monostack to keep track of all indices where the height is taller than the height at stack top index. If the incoming height is shorter than the stack top's, we pop the stack, calculate the area which equals to height[popedIndex] * (i-(topIndex+1)), and update the max area. To avoid to make the monostack empty or left elements after the loop, we add 0s to the front and the back of the input array.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(n)O(n)

Code

Reference

Last updated

Was this helpful?