84.柱状图中最大的矩形
84.柱状图中最大的矩形
题解
思路:利用栈存下标,如果当前的高小于栈内idx对应的高,则计算idx延展开来的面积,官方题解视频看到9:08即可
代码
package main func largestRectangleArea(heights []int) int { if len(heights) == 0 { return 0 } var stack []int max := 0 for i := 0; i <= len(heights); i++ { var cur int if i == len(heights) { cur = 0 } else { cur = heights[i] } for len(stack) != 0 && cur <= heights[stack[len(stack)-1]] { idx := stack[len(stack)-1] stack = stack[:len(stack)-1] h := heights[idx] peek := 0 w := i if len(stack) != 0 { peek = stack[len(stack)-1] w = i - peek - 1 } max = Max(max, w*h) } stack = append(stack, i) } return max } func Max(a, b int) int { if a > b { return a } return b } func main() { }