2026-01-16 Daily Challenge
Today I have done leetcode's January LeetCoding Challenge with cpp.
January LeetCoding Challenge 16
Description
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.
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 <= 1091 <= hFences.length, vFences.length <= 6001 < hFences[i] < m1 < vFences[i] < nhFencesandvFencesare unique.
Solution
class Solution {
const int MOD = 1e9 + 7;
unordered_set<int> getLengths(vector<int> &fences, int border) {
unordered_set<int> st;
fences.push_back(1);
fences.push_back(border);
sort(fences.begin(), fences.end());
int sz = fences.size();
for(int i = 0; i < sz - 1; ++i) {
for(int j = i + 1; j < sz; ++j) {
st.insert(fences[j] - fences[i]);
}
}
return st;
}
public:
int maximizeSquareArea(int m, int n, vector<int>& hFences, vector<int>& vFences) {
auto hLengths = getLengths(hFences, m);
auto vLengths = getLengths(vFences, n);
int side = 0;
for(auto hl : hLengths) {
if(vLengths.count(hl)) side = max(side, hl);
}
if(side == 0) return -1;
return 1LL * side * side % MOD;
}
};
// Accepted
// 648/648 cases passed (1806 ms)
// Your runtime beats 22.88 % of cpp submissions
// Your memory usage beats 9.8 % of cpp submissions (445.9 MB)