// 84.柱状图中最大的矩形
package mainimport "fmt"func largestRectangleArea(heights []int) int {// 初始化单调栈(单调递减栈)stack := []int{0}res := 0// 给原数组首位添加0// 数组头部加入0heights = append([]int{0}, heights...)// 数组尾部加入0heights = append(heights, 0)for i := 1; i < len(heights); i++ {top := stack[len(stack)-1]if heights[i] >= heights[top] {stack = append(stack, i)} else {for len(stack) != 0 && heights[i] < heights[top] {mid := topstack = stack[:len(stack)-1]if len(stack) != 0 {top = stack[len(stack)-1]left := topright := iw := right - left - 1h := heights[mid]res = max(w*h, res)}}stack = append(stack, i)}}return res
}
func max(a, b int) int {if a > b {return a}return b
}
func main() {heights := []int{2, 1, 5, 6, 2, 3}res := largestRectangleArea(heights)fmt.Printf("res: %v\n", res) //res:10
}