#3000

Maximum Area of Longest Diagonal Rectangle

Easy
ArrayArrayMathematics
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

We can achieve the same result in a single pass through the rectangles, calculating the diagonal and area simultaneously, which allows us to keep track of the maximum values efficiently.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize variables to track the maximum diagonal length and the corresponding maximum area.
  2. 2Step 2: Loop through each rectangle in the dimensions array.
  3. 3Step 3: Calculate the diagonal length and area in one go.
  4. 4Step 4: Update the maximum diagonal and area based on the conditions.
  5. 5Step 5: Return the maximum area found.
solution.py14 lines
1import math
2
3def maxAreaOfLongestDiagonal(dimensions):
4    max_diagonal = 0
5    max_area = 0
6    for length, width in dimensions:
7        diagonal = math.sqrt(length ** 2 + width ** 2)
8        area = length * width
9        if diagonal > max_diagonal:
10            max_diagonal = diagonal
11            max_area = area
12        elif diagonal == max_diagonal:
13            max_area = max(max_area, area)
14    return max_area

Complexity note: The time complexity remains O(n) as we still loop through each rectangle once, and the space complexity is O(1) since we only store a few variables.

  • 1The diagonal length is calculated using the Pythagorean theorem.
  • 2When diagonals are equal, the area becomes the deciding factor.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.