84. Largest Rectangle in Histogram

Givennnon-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height =[2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area =10unit.

For example, Given heights =[2,1,5,6,2,3], return10.

Thoughts:

  1. have a stack to record increasing index

  2. while current index is less that the top of the stack, update the maximum area

  3. having a increasing stack is because as index gets larger, the only possible way for rectangle starting from larger index is due to its larger height value.

Code time complexity: O(n), space complexity: O(n)

Code using 0 padding at the end and vector as stack

Special thanks to sipiprotoss5's for the last solution

Last updated

Was this helpful?