Maximum Square Area by Removing Fences From a Field Problem
Description
LeetCode Problem 2975.
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 10^9+ 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:

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:

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:
3 <= m, n <= 10^91 <= hFences.length, vFences.length <= 6001 < hFences[i] < m1 < vFences[i] < nhFencesandvFencesare unique.
Solution
Approach: Enumeration
The field is bounded by fences at positions 1 and m (horizontal) and 1 and n (vertical), which can never be removed. Any two horizontal fences, among the given ones plus the boundaries, can become the top and bottom of the field, so the possible heights are all pairwise differences. Collect them in a hash set hs, and do the same for the vertical fences into vs.
A square of side d is possible exactly when d is in both sets. Take the largest such d and return d^2 modulo 10^9 + 7, or -1 if there is no common distance.
The time complexity is O(h^2 + v^2) and the space complexity is O(h^2 + v^2), where h and v are the lengths of hFences and vFences.
from itertools import combinations
class Solution:
def maximizeSquareArea(
self, m: int, n: int, hFences: List[int], vFences: List[int]
) -> int:
def f(nums: List[int], k: int) -> Set[int]:
nums.extend([1, k])
nums.sort()
return {b - a for a, b in combinations(nums, 2)}
mod = 10**9 + 7
hs = f(hFences, m)
vs = f(vFences, n)
ans = max(hs & vs, default=0)
return ans**2 % mod if ans else -1