File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int maximalRectangle (char [][] matrix ) {
3+ if (matrix == null || matrix .length == 0 ) {
4+ return 0 ;
5+ }
6+
7+ int [] heights = new int [matrix [0 ].length ];
8+ int max = 0 ;
9+
10+ for (int i = 0 ; i < matrix .length ; i ++) {
11+ for (int j = 0 ; j < matrix [i ].length ; j ++) {
12+ if (matrix [i ][j ] == '0' ) {
13+ heights [j ] = 0 ;
14+ } else {
15+ heights [j ] += 1 ;
16+ }
17+ }
18+
19+ int area = largestRectangleArea (heights );
20+ max = Math .max (max , area );
21+ }
22+
23+ return max ;
24+ }
25+
26+ private int largestRectangleArea (int [] heights ) {
27+ int n = heights .length ;
28+ int max = 0 ;
29+ Stack <Integer > s = new Stack <>();
30+
31+ for (int i = 0 ; i <= n ; i ++) {
32+ int h = i == n ? 0 : heights [i ];
33+
34+ while (!s .isEmpty () && heights [s .peek ()] > h ) {
35+ int currHeight = heights [s .pop ()];
36+ int leftBoundary = s .isEmpty () ? -1 : s .peek ();
37+ int rightBoundary = i - 1 ;
38+ max = Math .max (max , currHeight * (rightBoundary - leftBoundary ));
39+ }
40+
41+ s .push (i );
42+ }
43+
44+ return max ;
45+ }
46+ }
You can’t perform that action at this time.
0 commit comments