-
Notifications
You must be signed in to change notification settings - Fork 0
/
085.go
75 lines (68 loc) · 1.51 KB
/
085.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package p085
/**
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle
containing only 1's and return its area.
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 6.
*/
func maximalRectangle(matrix [][]byte) int {
if len(matrix) == 0 {
return 0
}
heights := make([]int, len(matrix[0]))
max := -1
for i := 0; i < len(matrix); i++ {
for j := 0; j < len(matrix[i]); j++ {
if matrix[i][j] == '1' {
heights[j]++
} else {
heights[j] = 0
}
}
if largest := largestRectangleArea(heights); largest > max {
max = largest
}
}
return max
}
func largestRectangleArea(heights []int) int {
if heights == nil || len(heights) == 0 {
return 0
}
heightStack := make([]int, 0)
widthStack := make([]int, 0)
stackEnd := -1
largest := -1
for i := 0; i <= len(heights); i++ {
v := -1
if i < len(heights) {
v = heights[i]
}
if v > stackEnd {
heightStack = append(heightStack, v)
widthStack = append(widthStack, 1)
stackEnd = v
} else if v == stackEnd {
widthStack[len(widthStack)-1]++
} else {
h, w := 0, 0
for len(heightStack) > 0 && heightStack[len(heightStack)-1] >= v {
h = heightStack[len(heightStack)-1]
w += widthStack[len(widthStack)-1]
heightStack = heightStack[:len(heightStack)-1]
widthStack = widthStack[:len(widthStack)-1]
if h*w > largest {
largest = h * w
}
}
heightStack = append(heightStack, v)
widthStack = append(widthStack, w+1)
stackEnd = v
}
}
return largest
}