Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created January 16, 2026 18:23
Show Gist options
  • Select an option

  • Save tatsuyax25/fa5e74e00d6d1314e11924ccf68bcb0c to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/fa5e74e00d6d1314e11924ccf68bcb0c to your computer and use it in GitHub Desktop.
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 (hF
/**
* @param {number} m
* @param {number} n
* @param {number[]} hFences
* @param {number[]} vFences
* @return {number}
*/
var maximizeSquareArea = function(m, n, hFences, vFences) {
const MOD = 1_000_000_007;
/**
* Build a sorted list of all fence positions including the fixed boundaries,
* then compute ALL possible distances between any two fences.
*
* Example:
* boundaries: minBoundary = 1, maxBoundary = 10
* fences = [3, 7]
* positions = [1, 3, 7, 10]
* distances:
* 3-1 = 2, 7-1 = 6, 10-1 = 9
* 7-3 = 4, 10-3 = 7
* 10-7 = 3
* So we collect {2, 3, 4, 6, 7, 9}
*
* These distances represent all possible side lengths you can get
* by keeping just two fences and removing everything between them.
*/
function allDistances(fences, minBoundary, maxBoundary) {
const arr = [minBoundary, ...fences, maxBoundary];
arr.sort((a, b) => a - b);
const distances = new Set();
// Consider every pair (i, j) with i < j
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
const d = arr[j] - arr[i];
distances.add(d);
}
}
return distances;
}
// All possible horizontal side lengths (from y-coordinates)
const hDistances = allDistances(hFences, 1, m);
// All possible vertical side lengths (from x-coordinates)
const vDistances = allDistances(vFences, 1, n);
/**
* We now need the largest side length that exists in BOTH sets.
* That is, a distance that can be realized horizontally AND vertically.
*/
let maxSide = 0;
for (const d of hDistances) {
if (vDistances.has(d)) {
if (d > maxSide) maxSide = d;
}
}
// If no common side length > 0 exists, we cannot form a square
if (maxSide === 0) return -1;
// Compute area with BigInt to avoid overflow, then convert back to Number
const area = (BigInt(maxSide) * BigInt(maxSide)) % BigInt(MOD);
return Number(area);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment