Maximum Square Area by Removing Fences From a Field - Hashset on Fence Diffs [JS]

Description 

Solution: Hashset on Fence Diffs

Use a hashset to store the differences between each pair of horizontal fences.
Find any common fence differences between the horizontal and vertical fences, and record the maximum such difference.

h = length of hFencesv = length of vFences
Time Complexity: O(h^2 + v^2)
Space Complexity: O(h^2)

var maximizeSquareArea = function(m, n, hFences, vFences) {
  hFences.push(1), hFences.push(m);
  vFences.push(1), vFences.push(n);
  let hDiffs = new Set();
  for (let i = 0; i < hFences.length; i++) {
    for (let j = i + 1; j < hFences.length; j++) {
      let diff = Math.abs(hFences[i] - hFences[j]);
      hDiffs.add(diff);
    }
  }
  let maxDiff = 0;
  for (let i = 0; i < vFences.length; i++) {
    for (let j = i + 1; j < vFences.length; j++) {
      let diff = Math.abs(vFences[i] - vFences[j]);
      if (hDiffs.has(diff)) maxDiff = Math.max(maxDiff, diff);
    }
  }
  return maxDiff === 0 ? -1 : (BigInt(maxDiff) * BigInt(maxDiff)) % 1000000007n;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]