标签:ble str ola 题目 lan pen height max else
知识点:动态规划、单调栈
LeetCode第八十五题:https://leetcode-cn.com/problems/maximal-rectangle/submissions/
有些题目是真的难,比如这题,答案都不一定抄的明白。
语言:GoLang
// 结合LeetCode 84题,逐行计算。抽象问题并结合已有题目的想象力?太难了
func maximalRectangle(matrix [][]byte) int {
rowLen := len(matrix)
if rowLen == 0 {
return 0
}
colLen := len(matrix[0])
heightMat := make([][]int, rowLen)
for i := 0; i < rowLen; i++ {
heightMat[i] = make([]int, colLen)
}
for j := 0; j < colLen; j++ {
height := 0
for i := 0; i < rowLen; i++ {
if matrix[i][j] == ‘1‘ {
height++
} else {
height = 0
}
heightMat[i][j] = height
}
}
maxArea := 0
for i := 0; i < rowLen; i++ {
area := largestRectangleArea(heightMat[i])
if area > maxArea {
maxArea = area
}
}
return maxArea
}
func largestRectangleArea(heights []int) int {
heights = append(append([]int{0}, heights...), 0)
length := len(heights)
maxArea := 0
stack := make([]int, 0)
for i := 0; i < length; i++ {
size := len(stack)
for size > 0 && heights[i] < heights[stack[size - 1]] {
tmpHeight := stack[size - 1]
stack = stack[:size - 1]
size = len(stack)
area := (i - stack[size - 1] - 1) * heights[tmpHeight]
if maxArea < area {
maxArea = area
}
}
stack = append(stack, i)
}
return maxArea
}
标签:ble str ola 题目 lan pen height max else
原文地址:https://www.cnblogs.com/cenyol/p/13260047.html