Last active
August 26, 2025 17:06
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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