2021-03-19: Given a two-dimensional array matrix, where the value is either 0 or 1, return the largest sub-rectangle consisting of 1s and how many 1s are inside.
Fu Da's answer 2021-03-19:
Traverse the two-dimensional array row by row to construct a histogram.
Monotonous stack, big and small. There is code.
The code is written in golang, the code is as follows:
package main
import "fmt"
func main() {
matrix := [][]byte{
{1, 1, 1},
{1, 0, 1},
{1, 1, 1},
{1, 1, 1}}
ret := maximalRectangle(matrix)
fmt.Println(ret)
}
func maximalRectangle(matrix [][]byte) (ans int) {
rowsLen := len(matrix)
colsLen := len(matrix[0])
height := make([]int, colsLen)
maxArea := 0
for i := 0; i < rowsLen; i++ {
for j := 0; j < colsLen; j++ {
if matrix[i][j] == 0 {
height[j] = 0
} else {
height[j]++
}
maxArea = getMax(maxArea, largestRectangleArea(height))
}
}
return maxArea
}
func largestRectangleArea(height []int) int {
if len(height) == 0 {
return 0
}
N := len(height)
stack := make([]int, N)
si := -1
maxArea := 0
for i := 0; i < N; i++ {
for si != -1 && height[i] <= height[stack[si]] {
j := stack[si]
si--
k := 0
if si == -1 {
k = -1
} else {
k = stack[si]
}
curArea := (i - k - 1) * height[j]
maxArea = getMax(maxArea, curArea)
}
si++
stack[si] = i
}
for si != -1 {
j := stack[si]
si--
k := 0
if si == -1 {
k = -1
} else {
k = stack[si]
}
curArea := (N - k - 1) * height[j]
maxArea = getMax(maxArea, curArea)
}
return maxArea
}
func getMax(a int, b int) int {
if a > b {
return a
} else {
return b
}
}
The execution results are as follows: