Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Rectangles are ranked first by diagonal length and then, only when those lengths tie, by area. A single scan can retain the best candidate according to that ordering.
Approach
For each rectangle, calculate its diagonal from the Pythagorean theorem using its length and width. Compare that value with the longest diagonal seen so far. If it is longer, replace both the stored diagonal and the answer area with this rectangle's values. If it is equal, keep the larger of the current answer and this rectangle's area. Ignore shorter diagonals regardless of their areas.
After each iteration, the stored area belongs to the best rectangle in the processed prefix. Consequently, after all rectangles are examined, it is the maximum area among rectangles with a longest diagonal.
class Solution:
def areaOfMaxDiagonal(self, dimensions: List[List[int]]) -> int:
mx = 0
res = 0
for l, w in dimensions:
curr = sqrt(l**2 + w**2)
if curr == mx:
res = max(res, l * w)
elif curr > mx:
mx = curr
res = l * w
return resComplexity analysis
Let n = dimensions.length. Time: O(n). Auxiliary space: O(1).
