Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 104768c

Browse files
85. Maximal Rectangle
1 parent a691615 commit 104768c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

‎85.MaximalRectangle.kt‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
fun maximalRectangle(matrix: Array<CharArray>): Int {
3+
if (matrix.isEmpty() || matrix[0].isEmpty()) {
4+
return 0
5+
}
6+
val heights = IntArray(matrix[0].size)
7+
var maxArea = 0
8+
for (row in matrix) {
9+
for ((index, cell) in row.withIndex()) {
10+
heights[index] = if (cell == '1') heights[index] + 1 else 0
11+
}
12+
maxArea = maxOf(maxArea, maxRectangleInHistogram(heights))
13+
}
14+
return maxArea
15+
}
16+
fun maxRectangleInHistogram(heights: IntArray): Int {
17+
val stack = mutableListOf<Int>()
18+
var index = 0
19+
var maxArea = 0
20+
21+
while (index < heights.size) {
22+
if (stack.isEmpty() || heights[index] >= heights[stack.last()]) {
23+
stack.add(index++)
24+
} else {
25+
val top = stack.removeAt(stack.size - 1)
26+
val width = if (stack.isEmpty()) index else index - stack.last() - 1
27+
maxArea = maxOf(maxArea, heights[top] * width)
28+
}
29+
}
30+
while (stack.isNotEmpty()) {
31+
val top = stack.removeAt(stack.size - 1)
32+
val width = if (stack.isEmpty()) index else index - stack.last() - 1
33+
maxArea = maxOf(maxArea, heights[top] * width)
34+
}
35+
return maxArea
36+
}
37+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /