Given n rectangles represented as a list of four integers [x1, y1, x2, y2]
where (x1, y1)
is the bottom-left corner and (x2, y2)
is the top-right corner of the rectangle, determine the maximum area of the rectangle that can be formed from the longest diagonal of any rectangles.
x1 < x2
and y1 < y2
for every rectangle?The problem essentially boils down to two main steps:
(x1, y1)
and (x2, y2)
is d = sqrt((x2 - x1)^2 + (y2 - y1)^2)
.area = (x2 - x1) * (y2 - y1)
.Here’s a Python function to solve the problem:
import math
def max_area_longest_diagonal(rectangles):
max_diagonal = 0
max_area = 0
for rect in rectangles:
x1, y1, x2, y2 = rect
diagonal_length = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
area = (x2 - x1) * (y2 - y1)
if diagonal_length > max_diagonal:
max_diagonal = diagonal_length
max_area = area
return max_area
# Example usage:
rectangles = [
[1, 1, 4, 5],
[2, 3, 8, 7],
[3, 2, 5, 6]
]
print(max_area_longest_diagonal(rectangles)) # Output would be the area of rectangle with the longest diagonal
The time complexity for this solution is:
n
is the number of rectangles, since we are iterating through each rectangle once to calculate the diagonal and area.Each individual operation within the loop (calculating the diagonal, area, and checking conditions) is constant time, O(1). Therefore, the overall time complexity remains O(n).
This should ensure efficient handling even when n
is large.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?