- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 56 lines of Python from the credited upstream file maximize-area-of-square-hole-in-grid.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def maximizeSquareHoleArea(self, n, m, hBars, vBars):7 """8 :type n: int9 :type m: int10 :type hBars: List[int]11 :type vBars: List[int]12 :rtype: int13 """14 def max_gap(arr):15 result = l = 116 lookup = set(arr)17 while lookup:18 x = next(iter(lookup))19 left = x20 while left-1 in lookup:21 left -= 122 right = x23 while right+1 in lookup:24 right += 125 for i in xrange(left, right+1):26 lookup.remove(i)27 result = max(result, (right-left+1)+1)28 return result29 30 return min(max_gap(hBars), max_gap(vBars))**231 32 33343536class Solution2(object):37 def maximizeSquareHoleArea(self, n, m, hBars, vBars):38 """39 :type n: int40 :type m: int41 :type hBars: List[int]42 :type vBars: List[int]43 :rtype: int44 """45 def max_gap(arr):46 arr.sort()47 result = l = 148 for i in xrange(len(arr)):49 l += 150 result = max(result, l)51 if i+1 != len(arr) and arr[i+1] != arr[i]+1:52 l = 153 return result54 55 return min(max_gap(hBars), max_gap(vBars))**256