Created
April 13, 2024 16:42
-
-
Save tatsuyax25/cd2bbdcd4e372e6c6a4fd57853e1d2b8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {character[][]} matrix | |
| * @return {number} | |
| */ | |
| var maximalRectangle = function(matrix) { | |
| if (matrix.length === 0) return 0; // If the matrix is empty, return 0 | |
| var m = matrix.length; | |
| var n = matrix[0].length; | |
| var left = new Array(n).fill(0); // Initialize left, right and height arrays | |
| var right = new Array(n).fill(n); | |
| var height = new Array(n).fill(0); | |
| var maxArea = 0; | |
| for (var i = 0; i < m; i++) { | |
| var cur_left = 0, cur_right = n; | |
| // Update height | |
| for (var j = 0; j < n; j++) { | |
| if (matrix[i][j] === '1') height[j]++; | |
| else height[j] = 0; | |
| } | |
| // Update left | |
| for (var j = 0; j < n; j++) { | |
| if (matrix[i][j] === '1') left[j] = Math.max(left[j], cur_left); | |
| else { left[j] = 0; cur_left = j + 1; } | |
| } | |
| // Update right | |
| for (var j = n - 1; j >= 0; j--) { | |
| if (matrix[i][j] === '1') right[j] = Math.min(right[j], cur_right); | |
| else { right[j] = n; cur_right = j; } | |
| } | |
| // Update the area | |
| for (var j = 0; j < n; j++) | |
| maxArea = Math.max(maxArea, (right[j] - left[j]) * height[j]); | |
| } | |
| return maxArea; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment