3000. Maximum Area of Longest Diagonal Rectangle #2098
-
Topics: You are given a 2D 0-indexed integer array For all indices Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the area of the rectangle having the maximum area. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the rectangle with the longest diagonal from a given list of rectangles. If multiple rectangles have the same longest diagonal, we then select the one with the largest area. The solution involves calculating the diagonal length for each rectangle and comparing these lengths, while also considering the area in case of ties. Approach
Let's implement this solution in PHP: 3000. Maximum Area of Longest Diagonal Rectangle <?php
/**
* @param Integer[][] $dimensions
* @return Integer
*/
function areaOfMaxDiagonal($dimensions) {
$maxDiagonalSq = 0;
$maxArea = 0;
foreach ($dimensions as $rect) {
$l = $rect[0];
$w = $rect[1];
$diagonalSq = $l * $l + $w * $w;
$area = $l * $w;
if ($diagonalSq > $maxDiagonalSq) {
$maxDiagonalSq = $diagonalSq;
$maxArea = $area;
} elseif ($diagonalSq == $maxDiagonalSq) {
if ($area > $maxArea) {
$maxArea = $area;
}
}
}
return $maxArea;
}
// Test cases
// Example 1
$dimensions1 = array(array(9,3), array(8,6));
echo areaOfMaxDiagonal($dimensions1) . "\n"; // Output: 48
// Example 2
$dimensions2 = array(array(3,4), array(4,3));
echo areaOfMaxDiagonal($dimensions2) . "\n"; // Output: 12
?> Explanation:
This approach efficiently narrows down the candidate rectangles by leveraging simple arithmetic and comparisons, ensuring optimal performance even for the upper constraint limits. |
Beta Was this translation helpful? Give feedback.
We need to find the rectangle with the longest diagonal from a given list of rectangles. If multiple rectangles have the same longest diagonal, we then select the one with the largest area. The solution involves calculating the diagonal length for each rectangle and comparing these lengths, while also considering the area in case of ties.
Approach
diagonal = sqrt(length2 + width2)
. However, to avoid floating-point inaccuracies, we compare the squares of the diagonals (i.e.,length2 + width2