Skip to content

最大矩形 #73

Open
Open
@louzhedong

Description

习题

出处:LeetCode 算法第85题

给定一个仅包含 0 和 1 的二维二进制矩阵,找出只包含 1 的最大矩形,并返回其面积。

示例:

输入:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
输出: 6

解答

var maximalRectangle = function (matrix) {
  if (matrix.length == 0) return 0;
  var heights = new Array(matrix[0].length + 1).fill(0);
  var max = 0;
  matrix.forEach(function (line) {
    line.forEach(function (flag, i) {
      heights[i] = flag == '1' ? heights[i] + 1 : 0;
    })
    var stack = [[0, -1]];
    var top = 0;
    heights.forEach(function (height, index) {
      var current = index;
      while (stack[top][0] > height) {
        var [h, i] = stack.pop();
        max = Math.max(max, (index - i) * h)
        current = i;
        top--;
      }
      if (stack[top][0] < height) {
        stack.push([height, current]);
        top++;
      }
    })
  })
  return max;
};

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions