3000. Maximum Area of Longest Diagonal Rectangle
Description
You are given a 2D 0-indexed integer array dimensions.
For all indices i, 0 <= i < dimensions.length, dimensions[i][0] represents the length and dimensions[i][1] represents the width of the rectangle i.
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:
Input: dimensions = [[9,3],[8,6]] Output: 48 Explanation: For index = 0, length = 9 and width = 3. Diagonal length = sqrt(9 * 9 + 3 * 3) = sqrt(90) ≈ 9.487. For index = 1, length = 8 and width = 6. Diagonal length = sqrt(8 * 8 + 6 * 6) = sqrt(100) = 10. So, the rectangle at index 1 has a greater diagonal length therefore we return area = 8 * 6 = 48.
Example 2:
Input: dimensions = [[3,4],[4,3]] Output: 12 Explanation: Length of diagonal is the same for both which is 5, so maximum area = 12.
Constraints:
1 <= dimensions.length <= 100dimensions[i].length == 21 <= dimensions[i][0], dimensions[i][1] <= 100
Solutions
Solution 1: Mathematics
Thinking
There are at most \(100\) rectangles, so a linear scan of diagonals and areas is enough. Comparing square roots of the diagonals would introduce floating-point error.
The diagonal length is determined by \(l^2+w^2\), and the area is \(l \times w\). A strictly larger squared sum uniquely owns the longest diagonal; equal sums compete on area.
We therefore keep the best squared sum \(\textit{mx}\) and its area \(\textit{ans}\). When the squared sum grows we replace the area; when it ties we take the larger area.
According to the Pythagorean theorem, the square of the diagonal of a rectangle is \(l^2 + w^2\), where \(l\) and \(w\) are the length and width of the rectangle, respectively.
We can iterate through all the rectangles, calculate the square of their diagonal lengths, and keep track of the maximum diagonal length and the corresponding area.
After the iteration, we return the recorded maximum area.
The time complexity is \(O(n)\), where \(n\) is the number of rectangles. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |