Leetcode: Maximal Rectangle. java

Source: Internet
Author: User

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


The question requires only one rectangle.


The algorithm is to calculate the length of a line segment H [I] [j] that can be expanded to the left at each point. L [I] [j], position R [I] [j] that can be expanded to the right.

For point A, the length of the Red Arrow headers with A continuous upward direction of 1 is 4, H [4] [1] = 4. This Red Arrow expands to the left and right sides as a rectangle and can be moved to the leftmost position. L [4] [1] = 1, R [4] [1] = 2 (L included in the matrix, R not included ). The area of the rectangle corresponding to Vertex A is H * (R-L) = 4.

For point B, H [3] [2] = 3, L [3] [2] = 1, R [3] [2] = 4. The corresponding area H * (R-L) = 9. Traverse all vertices to obtain the largest area. Because only data of H, L, and R is used for calculation, one-dimensional arrays instead of two-dimensional arrays are used for calculation.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + PHByZSBjbGFzcz0 = "brush: java;"> public class Solution {public int maximalRectangle (char [] [] matrix) {if (matrix = null | matrix. length = 0) return 0; int m = matrix. length; int n = matrix [0]. length; int [] H = new int [n]; int [] L = new int [n]; int [] R = new int [n]; for (int I = 0; I <n; I ++) {L [I] = 0; H [I] = 0; R [I] = n ;} int res = 0; for (int I = 0; I <m; I ++) {int left = 0; int right = n; for (int j = 0; j <n; j ++) {if (matrix [I] [j] = '1') {H [j] ++; L [j] = Math. max (L [j], left) ;}else {H [j] = 0; L [j] = 0; R [j] = n; left = j + 1 ;}}for (int j = n-1; j> = 0; -- j) {if (matrix [I] [j] = '1') {R [j] = Math. min (R [j], right); res = Math. max (res, H [j] * (R [j]-L [j]);} else {right = j ;}} 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.