Approach
Sorting and greedy selection
For Maximum Square Area by Removing Fences From a Field, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 35 lines of Java from the credited upstream file 2975.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 3 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int maximizeSquareArea(int m, int n, int[] hFences, int[] vFences) {3 final int MOD = 1_000_000_007;4 5 hFences = Arrays.copyOf(hFences, hFences.length + 2);6 vFences = Arrays.copyOf(vFences, vFences.length + 2);7 8 hFences[hFences.length - 2] = 1;9 hFences[hFences.length - 1] = m;10 vFences[vFences.length - 2] = 1;11 vFences[vFences.length - 1] = n;12 13 Arrays.sort(hFences);14 Arrays.sort(vFences);15 16 Set<Integer> hGaps = getGaps(hFences);17 Set<Integer> vGaps = getGaps(vFences);18 int maxGap = -1;19 20 for (final int hGap : hGaps)21 if (vGaps.contains(hGap))22 maxGap = Math.max(maxGap, hGap);23 24 return maxGap == -1 ? -1 : (int) ((long) maxGap * maxGap % MOD);25 }26 27 private Set<Integer> getGaps(int[] fences) {28 Set<Integer> gaps = new HashSet<>();29 for (int i = 0; i < fences.length; ++i)30 for (int j = 0; j < i; ++j)31 gaps.add(fences[i] - fences[j]);32 return gaps;33 }34}35