Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Last active August 26, 2025 17:06
Show Gist options
  • Save tatsuyax25/24e39ed9ec1ff4d7181dbe8cecc32e98 to your computer and use it in GitHub Desktop.
Save tatsuyax25/24e39ed9ec1ff4d7181dbe8cecc32e98 to your computer and use it in GitHub Desktop.
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 l
/**
* Returns the area of the rectangle with the longest diagonal.
* If multiple rectangles share the longest diagonal, returns the one with the largest area.
*
* @param {number[][]} dimensions - Array of [length, width] pairs for each rectangle.
* @return {number} - Area of the rectangle with the longest diagonal.
*/
var areaOfMaxDiagonal = function(dimensions) {
let maxDiagonalSq = 0; // Stores the longest diagonal squared (avoids using Math.sqrt)
let maxArea = 0; // Stores the area of the rectangle with the longest diagonal
for (let i = 0; i < dimensions.length; i++) {
const [length, width] = dimensions[i];
// Calculate squared diagonal: length² + width²
const diagonalSq = length * length + width * width;
// Calculate area: length × width
const area = length * width;
// Update if this rectangle has a longer diagonal,
// or same diagonal but larger area
if (
diagonalSq > maxDiagonalSq ||
(diagonalSq === maxDiagonalSq && area > maxArea)
) {
maxDiagonalSq = diagonalSq;
maxArea = area;
}
}
return maxArea;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment