Skip to content

Commit

Permalink
A solution added for LC #85
Browse files Browse the repository at this point in the history
  • Loading branch information
rayworks committed Mar 11, 2024
1 parent 4ba4ef5 commit 03373ea
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
58 changes: 58 additions & 0 deletions src/main/java/org/sean/dynamicpro/MaxRectangle.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.sean.dynamicpro;

import java.util.Stack;

/***
* 85. Maximal Rectangle
*/
public class MaxRectangle {
private int[][] verticalSums;
private int maxArea = 0;

private void findMaxArea(int[] row) {
Stack<int[]> stack = new Stack<>();
for (int i = 0; i < row.length; i++) {
int len = row[i];
if (stack.isEmpty() || stack.peek()[1] < len) {
stack.push(new int[]{i, len});
} else {
// monotonic stack
int target = i;
while (!stack.isEmpty() && stack.peek()[1] >= len) {
int[] arr = stack.pop();
maxArea = Math.max(maxArea, arr[1] * (i - arr[0]));

// update the index for the new added item
target = arr[0];
}
stack.push(new int[]{target, len});
}
}
}

public int maximalRectangle(char[][] matrix) {
if (matrix == null || matrix.length == 0) {
return 0;
}

int rows = matrix.length;
int cols = matrix[0].length;

// extra row + column added for marking it as the end, all historical record will be evaluated.
verticalSums = new int[rows + 1][cols + 1];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] == '0') {
verticalSums[i][j] = 0;
} else {
verticalSums[i][j] = i > 0 ? verticalSums[i - 1][j] + 1 : 1;
}
}
}
for (int i = 0; i < rows; i++) {
findMaxArea(verticalSums[i]);
}

return maxArea;
}
}
27 changes: 27 additions & 0 deletions src/test/java/org/sean/dynamicpro/MaxRectangleTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.sean.dynamicpro;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class MaxRectangleTest {

private MaxRectangle rect;

@Before
public void setUp() throws Exception {
rect = new MaxRectangle();
}

@Test
public void maximalRectangle() {
int res = rect.maximalRectangle(new char[][]{
{'1', '0', '1', '0', '0'},
{'1', '0', '1', '1', '1'},
{'1', '1', '1', '1', '1'},
{'1', '0', '0', '1', '0'}
});
assertEquals(6, res);
}
}

0 comments on commit 03373ea

Please sign in to comment.