#2975
Maximum Square Area by Removing Fences From a Field
MediumArrayHash TableEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution leverages the differences between the fences to quickly determine the maximum square area without checking every pair. By calculating the maximum gaps between fences, we can directly derive the largest possible square.
⚙️
Algorithm
4 steps- 1Step 1: Include the boundaries (1 and m for horizontal, 1 and n for vertical) into hFences and vFences.
- 2Step 2: Sort both hFences and vFences.
- 3Step 3: Calculate the maximum height and width by finding the maximum differences between consecutive fences.
- 4Step 4: The maximum square area is the minimum of the maximum height and width squared.
solution.py10 lines
1# Full working Python code
2
3def maxSquareArea(m, n, hFences, vFences):
4 hFences = [1] + sorted(hFences) + [m]
5 vFences = [1] + sorted(vFences) + [n]
6 max_height = max(hFences[i + 1] - hFences[i] for i in range(len(hFences) - 1))
7 max_width = max(vFences[i + 1] - vFences[i] for i in range(len(vFences) - 1))
8 max_side = min(max_height, max_width)
9 return (max_side * max_side) % (10**9 + 7) if max_side > 0 else -1
10ℹ
Complexity note: The complexity is O(n log n) due to sorting the fences, while the space complexity is O(n) for storing the modified fence arrays.
- 1Understanding the relationship between the gaps created by fences and the maximum area of squares is crucial.
- 2Sorting the fences allows for efficient calculation of maximum gaps.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.