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 thearea 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.
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.
The diagonal of a rectangle with sides a and b is sqrt(a^2 + b^2). To find the rectangle with the longest diagonal, we can compare the squared diagonals (to avoid floating-point errors). If multiple rectangles have the same diagonal, we pick the one with the largest area.
classSolution {
public:int areaOfMaxDiagonal(vector<vector<int>>& dimensions) {
int maxDiag =0, ans =0;
for (auto& d : dimensions) {
int diag = d[0]*d[0] + d[1]*d[1];
int area = d[0]*d[1];
if (diag > maxDiag) {
maxDiag = diag;
ans = area;
} elseif (diag == maxDiag) {
ans = max(ans, area);
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcareaOfMaxDiagonal(dimensions [][]int) int {
maxDiag, ans:=0, 0for_, d:=rangedimensions {
diag:=d[0]*d[0] +d[1]*d[1]
area:=d[0]*d[1]
ifdiag > maxDiag {
maxDiag = diagans = area } elseifdiag==maxDiag&&area > ans {
ans = area }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintareaOfMaxDiagonal(int[][] dimensions) {
int maxDiag = 0, ans = 0;
for (int[] d : dimensions) {
int diag = d[0]*d[0]+ d[1]*d[1];
int area = d[0]*d[1];
if (diag > maxDiag) {
maxDiag = diag;
ans = area;
} elseif (diag == maxDiag) {
ans = Math.max(ans, area);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funareaOfMaxDiagonal(dimensions: Array<IntArray>): Int {
var maxDiag = 0var ans = 0for (d in dimensions) {
val diag = d[0]*d[0] + d[1]*d[1]
val area = d[0]*d[1]
if (diag > maxDiag) {
maxDiag = diag
ans = area
} elseif (diag == maxDiag) {
ans = maxOf(ans, area)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defareaOfMaxDiagonal(self, dimensions: list[list[int]]) -> int:
max_diag =0 ans =0for a, b in dimensions:
diag = a*a + b*b
area = a*b
if diag > max_diag:
max_diag = diag
ans = area
elif diag == max_diag:
ans = max(ans, area)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnarea_of_max_diagonal(dimensions: Vec<Vec<i32>>) -> i32 {
letmut max_diag =0;
letmut ans =0;
for d in dimensions {
let diag = d[0]*d[0] + d[1]*d[1];
let area = d[0]*d[1];
if diag > max_diag {
max_diag = diag;
ans = area;
} elseif diag == max_diag && area > ans {
ans = area;
}
}
ans
}
}