206k views
0 votes
Given is a polygon with n vertices (x₁, y₁), (x₂, y₂), . . . , (xₙ, yₙ) consisting of adjacent vertical towers. More precisely, n is even and the line segments alternate between vertical and horizontal (that is, x₂ i−1 = x₂i for every i ∈ {1, . . . , n/2}, and y₂i = y₂i+1 for every i ∈ {1, . . . , n/2 − 1}. Additionally, y₁ = y_n = 0, every other y-coordinate is positive (yᵢ > 0 for every y ∈ {2, . . . , n − 1}), and the x-coordinates form a non-decreasing sequence (that is, x₁ ≤ x₂ ≤ x₃ ≤ . . . ≤ xₙ). Design an O(n) algorithm in Java that finds the largest possible area of an axis parallel rectangle that fits inside this polygon.

User Yser
by
7.4k points

1 Answer

5 votes

Final answer:

To find the largest possible area of an axis parallel rectangle that fits inside the given polygon, iterate through each pair of adjacent vertical towers and calculate the area of the rectangle formed by their x-coordinates and the minimum y-coordinate.

Step-by-step explanation:

To find the largest possible area of an axis parallel rectangle that fits inside the given polygon, we can use a simple algorithm:

  1. Initialize the maximum area to 0.
  2. Iterate through each pair of adjacent vertical towers in the polygon.
  3. Calculate the width of the rectangle as the difference between the x-coordinates of the towers.
  4. Find the minimum y-coordinate between the towers and compute the height of the rectangle as the difference between this minimum y-coordinate and 0.
  5. Calculate the area of the rectangle as the product of the width and height, and update the maximum area if necessary.
  6. Return the maximum area.

This algorithm has a time complexity of O(n) since we iterate through each pair of adjacent vertical towers once.

User Fuad All
by
8.4k points