[LeetCode] Maximum Square Area by Removing Fences From a Field

10036. Maximum Square Area by Removing Fences From a Field

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
int maximizeSquareArea(int m, int n, vector<int>& A, vector<int>& B) {
A.push_back(1);
A.push_back(m);
B.push_back(1);
B.push_back(n);
sort(begin(A), end(A));
sort(begin(B), end(B));
unordered_set<int> da;
for(int i = 0; i < A.size(); i++) {
for(int j = i + 1; j < A.size(); j++) {
da.insert(A[j] - A[i]);
}
}
long long res = -1, mod = 1e9 + 7;
for(int i = 0; i < B.size(); i++) {
for(int j = i + 1; j < B.size(); j++) {
long long d = B[j] - B[i];
if(da.count(d)) res = max(res, d);
}
}
if(res == -1) return -1;
return res * res % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/24/PS/LeetCode/maximum-square-area-by-removing-fences-from-a-field/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.