Files
interview/16-LeetCode Hot 100/柱状图中最大的矩形.md
yasinshaw 15dbd75004 refactor: remove Java code sections from all LeetCode Hot 100 markdown files
- Remove all "## Java 解法" sections and Java code blocks
- Replace "## Go 解法" with "## 解法"
- Remove "### Go 代码要点" and "### Java 代码要点" sections
- Keep all Go code sections intact
- Maintain complete documentation structure and content
- Update 22 markdown files in the LeetCode Hot 100 directory
2026-03-05 12:31:48 +08:00

1.2 KiB

柱状图中最大的矩形 (Largest Rectangle in Histogram)

题目描述

给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1。

求在该柱状图中,能够勾勒出来的矩形的最大面积。

解题思路

方法一:单调栈(推荐)

**核心思想:**使用单调递增栈,存储柱子的索引。当遇到比栈顶小的柱子时,弹出栈顶并计算面积。

代码实现

Go 实现

package main

func largestRectangleArea(heights []int) int {
	stack := []int{}
	maxArea := 0
	n := len(heights)

	for i := 0; i <= n; i++ {
		h := 0
		if i < n {
			h = heights[i]
		}

		for len(stack) > 0 && h < heights[stack[len(stack)-1]] {
			height := heights[stack[len(stack)-1]]
			stack = stack[:len(stack)-1]

			width := i
			if len(stack) > 0 {
				width = i - stack[len(stack)-1] - 1
			}

			area := height * width
			if area > maxArea {
				maxArea = area
			}
		}

		stack = append(stack, i)
	}

	return maxArea
}

Java 实现

复杂度分析

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

P7 加分项

相关题目

  • LeetCode 85: 最大矩形(二维版本)
  • LeetCode 42: 接雨水