File tree Expand file tree Collapse file tree 1 file changed +77
-0
lines changed
Expand file tree Collapse file tree 1 file changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ # 85. Maximal Rectangle
2+
3+ - Difficulty: Hard.
4+ - Related Topics: Array, Hash Table, Dynamic Programming, Stack.
5+ - Similar Questions: Largest Rectangle in Histogram, Maximal Square.
6+
7+ ## Problem
8+
9+ Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
10+
11+ ** Example:**
12+
13+ ```
14+ Input:
15+ [
16+ ["1","0","1","0","0"],
17+ ["1","0","1","1","1"],
18+ ["1","1","1","1","1"],
19+ ["1","0","0","1","0"]
20+ ]
21+ Output: 6
22+ ```
23+
24+ ## Solution
25+
26+ ``` javascript
27+ /**
28+ * @param {character[][]} matrix
29+ * @return {number}
30+ */
31+ var maximalRectangle = function (matrix ) {
32+ var n = matrix .length ;
33+ var m = (matrix[0 ] || []).length ;
34+ var max = 0 ;
35+ var heights = Array (m);
36+ var stack = [];
37+ var h = 0 ;
38+ var w = 0 ;
39+
40+ for (var i = 0 ; i < n; i++ ) {
41+ stack = [];
42+
43+ for (var j = 0 ; j < m; j++ ) {
44+ if (matrix[i][j] === ' 1' ) {
45+ heights[j] = i === 0 ? 1 : heights[j] + 1 ;
46+ } else {
47+ heights[j] = 0 ;
48+ }
49+
50+ while (stack .length && heights[j] <= heights[stack[stack .length - 1 ]]) {
51+ h = heights[stack .pop ()];
52+ w = stack .length === 0 ? j : j - stack[stack .length - 1 ] - 1 ;
53+ max = Math .max (max, h * w);
54+ }
55+
56+ stack .push (j);
57+ }
58+
59+ while (stack .length ) {
60+ h = heights[stack .pop ()];
61+ w = stack .length === 0 ? m : m - stack[stack .length - 1 ] - 1 ;
62+ max = Math .max (max, h * w);
63+ }
64+ }
65+
66+ return max;
67+ };
68+ ```
69+
70+ ** Explain:**
71+
72+ see [ Largest Rectangle in Histogram] ( ./largest-rectangle-in-histogram.html ) .
73+
74+ ** Complexity:**
75+
76+ * Time complexity : O(n^2).
77+ * Space complexity : O(n).
You can’t perform that action at this time.
0 commit comments