Maximal Rectangle

描述

Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.

分析

代码

  1. // Maximal Rectangle
  2. // 时间复杂度O(n^2),空间复杂度O(n)
  3. public class Solution {
  4. public int maximalRectangle(char[][] matrix) {
  5. if (matrix.length == 0) return 0;
  6. final int m = matrix.length;
  7. final int n = matrix[0].length;
  8. int[] H = new int[n];
  9. int[] L = new int[n];
  10. int[] R = new int[n];
  11. Arrays.fill(R, n);
  12. int ret = 0;
  13. for (int i = 0; i < m; ++i) {
  14. int left = 0, right = n;
  15. // calculate L(i, j) from left to right
  16. for (int j = 0; j < n; ++j) {
  17. if (matrix[i][j] == '1') {
  18. ++H[j];
  19. L[j] = Math.max(L[j], left);
  20. } else {
  21. left = j+1;
  22. H[j] = 0; L[j] = 0; R[j] = n;
  23. }
  24. }
  25. // calculate R(i, j) from right to left
  26. for (int j = n-1; j >= 0; --j) {
  27. if (matrix[i][j] == '1') {
  28. R[j] = Math.min(R[j], right);
  29. ret = Math.max(ret, H[j]*(R[j]-L[j]));
  30. } else {
  31. right = j;
  32. }
  33. }
  34. }
  35. return ret;
  36. }
  37. }

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/dp/maximal-rectangle.html