Post

3250 Maximum Square Area By Removing Fences From A Field

3250 Maximum Square Area By Removing Fences From A Field

Maximum Square Area by Removing Fences From a Field image

There is a large (m - 1) x (n - 1) rectangular field with corners at (1, 1) and (m, n) containing some horizontal and vertical fences given in arrays hFences and vFences respectively.

Horizontal fences are from the coordinates (hFences[i], 1) to (hFences[i], n) and vertical fences are from the coordinates (1, vFences[i]) to (m, vFences[i]).

Return the maximum area of a square field that can be formed by removing some fences (possibly none) or *-1 *if it is impossible to make a square field.

Since the answer may be large, return it modulo 109 + 7.

Note: **The field is surrounded by two horizontal fences from the coordinates (1, 1) to (1, n) and (m, 1) to (m, n) and two vertical fences from the coordinates (1, 1) to (m, 1) and (1, n) to (m, n). These fences **cannot be removed.

 

Example 1:

image

1
2
3
4
5
**Input:** m = 4, n = 3, hFences = [2,3], vFences = [2]
**Output:** 4
**Explanation:** Removing the horizontal fence at 2 and the vertical fence at 2 will give a square field of area 4.

Example 2:

image

1
2
3
4
5
**Input:** m = 6, n = 7, hFences = [2], vFences = [4]
**Output:** -1
**Explanation:** It can be proved that there is no way to create a square field by removing fences.

 

Constraints:

1
2
3
4
5
3 <= m, n <= 109
1 <= hFences.length, vFences.length <= 600
1 < hFences[i] < m
1 < vFences[i] < n
hFences and vFences are unique.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

class Solution:
    def get_edges(self, fences: List[int], border: int) -> set:
        points = sorted([1] + fences + [border])
        return {
            points[j] - points[i]
            for i in range(len(points))
            for j in range(i + 1, len(points))
        }

    def maximizeSquareArea(
        self, m: int, n: int, hFences: List[int], vFences: List[int]
    ) -> int:
        MOD = 10**9 + 7
        h_edges = self.get_edges(hFences, m)
        v_edges = self.get_edges(vFences, n)

        max_edge = max(h_edges & v_edges, default=0)
        return (max_edge * max_edge) % MOD if max_edge else -1



This post is licensed under CC BY 4.0 by the author.