leetcode

Maximum Area of Longest Diagonal Rectangle - Link

Question Description

Given a 2D array dimensions where dimensions[i] = [length, width] represents the dimensions of the i-th rectangle. Return the area of the rectangle having the longest diagonal. If there are multiple rectangles with the longest diagonal, return the one with the largest area.


Constraints


Approach


Dry Run

Example Input: dimensions = [[9,3],[8,6]]

Step-by-step execution:

Final Answer = 48


Solution

class Solution {
    public int areaOfMaxDiagonal(int[][] dimensions) {
        int maxDiaSq = 0;  // store squared diagonal
        int maxArea = 0;

        for (int[] arr : dimensions) {
            int diaSq = arr[0] * arr[0] + arr[1] * arr[1];
            int area = arr[0] * arr[1];

            if (diaSq > maxDiaSq) {
                maxDiaSq = diaSq;
                maxArea = area;
            } else if (diaSq == maxDiaSq && area > maxArea) {
                maxArea = area;
            }
        }

        return maxArea;
    }
}

Time and Space Complexity