DevPath

← All problems

Largest Rectangle in Histogram

Hard stack · arrays

Description

Given bar heights of width 1, return the area of the largest rectangle that fits entirely within the histogram.

Constraints

1 <= n <= 100000; 0 <= height

Examples

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

Output: 10

Hints (1)
  • Use an increasing stack of indices; when a shorter bar appears, pop and compute width.

Solutions

Increasing stack with a sentinel 0 at the end. · Time O(n) · Space O(n)

func largestRectangleArea(heights []int) int {
    h := append(append([]int{}, heights...), 0)
    stack := []int{}
    best := 0
    for i, height := range h {
        for len(stack) > 0 && h[stack[len(stack)-1]] >= height {
            top := h[stack[len(stack)-1]]
            stack = stack[:len(stack)-1]
            left := 0
            if len(stack) > 0 {
                left = stack[len(stack)-1] + 1
            }
            if area := top * (i - left); area > best {
                best = area
            }
        }
        stack = append(stack, i)
    }
    return best
}

Create a free account to submit solutions, track progress and save problems.

Create account