85. Maximal Rectangle #57
-
Topics: Given a Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We can follow a dynamic programming approach. This problem can be effectively tackled by treating each row of the matrix as the base of a histogram, where the height of each column in the histogram represents the number of consecutive '1's up to that row.
Let's implement this solution in PHP: 85. Maximal Rectangle <?php
function maximalRectangle($matrix) {
if (empty($matrix) || empty($matrix[0])) {
return 0;
}
$rows = count($matrix);
$cols = count($matrix[0]);
// Create a height array for histogram
$height = array_fill(0, $cols, 0);
$maxArea = 0;
for ($i = 0; $i < $rows; $i++) {
// Update height array
for ($j = 0; $j < $cols; $j++) {
$height[$j] = $matrix[$i][$j] == '1' ? $height[$j] + 1 : 0;
}
// Calculate the max area for this row's histogram
$maxArea = max($maxArea, calculateMaxHistogramArea($height));
}
return $maxArea;
}
function calculateMaxHistogramArea($heights) {
$stack = array();
$maxArea = 0;
$index = 0;
while ($index < count($heights)) {
if (empty($stack) || $heights[$index] >= $heights[end($stack)]) {
array_push($stack, $index++);
} else {
$topOfStack = array_pop($stack);
$area = $heights[$topOfStack] * (empty($stack) ? $index : $index - end($stack) - 1);
$maxArea = max($maxArea, $area);
}
}
while (!empty($stack)) {
$topOfStack = array_pop($stack);
$area = $heights[$topOfStack] * (empty($stack) ? $index : $index - end($stack) - 1);
$maxArea = max($maxArea, $area);
}
return $maxArea;
}
// Test cases
$matrix1 = array(
array("1","0","1","0","0"),
array("1","0","1","1","1"),
array("1","1","1","1","1"),
array("1","0","0","1","0")
);
$matrix2 = array(
array("0")
);
$matrix3 = array(
array("1")
);
echo maximalRectangle($matrix1) . "\n"; // Output: 6
echo maximalRectangle($matrix2) . "\n"; // Output: 0
echo maximalRectangle($matrix3) . "\n"; // Output: 1
?> Explanation:
The |
Beta Was this translation helpful? Give feedback.
We can follow a dynamic programming approach. This problem can be effectively tackled by treating each row of the matrix as the base of a histogram, where the height of each column in the histogram represents the number of consecutive '1's up to that row.
1
s up to that row.Let's implement this solution in PHP: 85. Maximal Rectangle