[LeetCode] Maximal Rectangle

Source: Internet
Author: User

[LeetCode] 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.

Dynamic Planning

Use the left [] array to record the 1 distance from this point to the leftmost (inside the rectangle), and use the right [] array to record the 1 distance from this point to the rightmost (inside the rectangle, height [] records the maximum height of 1 in the rectangle of the vertex.



public class Solution {public int maximalRectangle(char[][] matrix) {if (matrix.length == 0)return 0;int row = matrix.length;int column = matrix[0].length;int left[] = new int[column], right[] = new int[column], height[] = new int[column];Arrays.fill(right, column-1);int res = 0;for (int i = 0; i < row; i++) {int l = 0, r = column - 1;for (int j = 0; j < column; j++) {if (matrix[i][j] == '1') {left[j] = Math.max(left[j], l);height[j]++;} else {l = j+1;left[j] =0;height[j] = 0;right[j] = column - 1;}}for (int j = column - 1; j >= 0; j--) {if (matrix[i][j] == '1') {right[j] = Math.min(r, right[j]);res = Math.max(res, height[j] * (right[j] - left[j]+1));} else {r = j-1;}}}return res;}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.