Skip to content

2975. Maximum Square Area by Removing Fences From a Field

  • Time: $O(|\texttt{hFences}|^2 + |\texttt{vFences}|^2)$
  • Space: $O(|\texttt{hFences}|^2 + |\texttt{vFences}|^2)$
 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
27
28
29
30
31
32
33
34
class Solution {
 public:
  int maximizeSquareArea(int m, int n, vector<int>& hFences,
                         vector<int>& vFences) {
    constexpr int kMod = 1'000'000'007;

    hFences.push_back(1);
    hFences.push_back(m);
    vFences.push_back(1);
    vFences.push_back(n);

    ranges::sort(hFences);
    ranges::sort(vFences);

    const unordered_set<int> hGaps = getGaps(hFences);
    const unordered_set<int> vGaps = getGaps(vFences);
    int maxGap = -1;

    for (const int hGap : hGaps)
      if (vGaps.contains(hGap))
        maxGap = max(maxGap, hGap);

    return maxGap == -1 ? -1 : static_cast<long>(maxGap) * maxGap % kMod;
  }

 private:
  unordered_set<int> getGaps(const vector<int>& fences) {
    unordered_set<int> gaps;
    for (int i = 0; i < fences.size(); ++i)
      for (int j = 0; j < i; ++j)
        gaps.insert(fences[i] - fences[j]);
    return gaps;
  }
};
 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
27
28
29
30
31
32
33
34
class Solution {
  public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) {
    final int kMod = 1_000_000_007;

    hFences = Arrays.copyOf(hFences, hFences.length + 2);
    vFences = Arrays.copyOf(vFences, vFences.length + 2);

    hFences[hFences.length - 2] = 1;
    hFences[hFences.length - 1] = m;
    vFences[vFences.length - 2] = 1;
    vFences[vFences.length - 1] = n;

    Arrays.sort(hFences);
    Arrays.sort(vFences);

    Set<Integer> hGaps = getGaps(hFences);
    Set<Integer> vGaps = getGaps(vFences);
    int maxGap = -1;

    for (final int hGap : hGaps)
      if (vGaps.contains(hGap))
        maxGap = Math.max(maxGap, hGap);

    return maxGap == -1 ? -1 : (int) ((long) maxGap * maxGap % kMod);
  }

  private Set<Integer> getGaps(int[] fences) {
    Set<Integer> gaps = new HashSet<>();
    for (int i = 0; i < fences.length; ++i)
      for (int j = 0; j < i; ++j)
        gaps.add(fences[i] - fences[j]);
    return gaps;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
  def maximizeSquareArea(
      self,
      m: int,
      n: int,
      hFences: list[int],
      vFences: list[int],
  ) -> int:
    hFences = sorted(hFences + [1, m])
    vFences = sorted(vFences + [1, n])
    hGaps = {hFences[i] - hFences[j]
             for i in range(len(hFences))
             for j in range(i)}
    vGaps = {vFences[i] - vFences[j]
             for i in range(len(vFences))
             for j in range(i)}
    maxGap = next((hGap
                  for hGap in sorted(hGaps, reverse=True)
                  if hGap in vGaps), -1)
    return -1 if maxGap == -1 else maxGap**2 % (10**9 + 7)