Skip to content

2975. Maximum Square Area by Removing Fences From a Field

Description

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 <= 109
  • ences

 

Solutions

Solution: Greedy

  • Time complexity: O(h2+v2)
    • h = hFences.length
    • v = vFences.length
  • Space complexity: O(h2+v2)

 

JavaScript

js
/**
 * @param {number} m
 * @param {number} n
 * @param {number[]} hFences
 * @param {number[]} vFences
 * @return {number}
 */
const maximizeSquareArea = function (m, n, hFences, vFences) {
  hFences.sort((a, b) => a - b);
  vFences.sort((a, b) => a - b);

  const MODULO = BigInt(10 ** 9 + 7);
  const rowFences = [1, ...hFences, m];
  const colFences = [1, ...vFences, n];
  const rowWidthSet = new Set();
  let maxWidth = 0;

  for (let a = 0; a < rowFences.length; a++) {
    for (let b = a + 1; b < rowFences.length; b++) {
      const width = rowFences[b] - rowFences[a];

      rowWidthSet.add(width);
    }
  }

  for (let a = 0; a < colFences.length; a++) {
    for (let b = a + 1; b < colFences.length; b++) {
      const width = colFences[b] - colFences[a];

      if (rowWidthSet.has(width)) {
        maxWidth = Math.max(width, maxWidth);
      }
    }
  }

  if (maxWidth === 0) return -1;

  const area = BigInt(maxWidth) ** 2n;

  return Number(area % MODULO);
};

Released under the MIT license