- Remove all "### Java 实现" sections from all markdown files - Clean up remaining Java code blocks and references - Ensure only Go code remains in all documentation - Complete the Java to Go migration for all 22 files
58 lines
1.1 KiB
Markdown
58 lines
1.1 KiB
Markdown
# 柱状图中最大的矩形 (Largest Rectangle in Histogram)
|
|
|
|
## 题目描述
|
|
|
|
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1。
|
|
|
|
求在该柱状图中,能够勾勒出来的矩形的最大面积。
|
|
|
|
## 解题思路
|
|
|
|
### 方法一:单调栈(推荐)
|
|
|
|
**核心思想:**使用单调递增栈,存储柱子的索引。当遇到比栈顶小的柱子时,弹出栈顶并计算面积。
|
|
|
|
## 代码实现
|
|
|
|
### Go 实现
|
|
|
|
```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
|
|
}
|
|
```
|
|
|
|
|
|
- LeetCode 85: 最大矩形(二维版本)
|
|
- LeetCode 42: 接雨水
|