- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 52 lines of C++ from the credited upstream file maximize-area-of-square-hole-in-grid.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
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 {6public:7 int maximizeSquareHoleArea(int n, int m, vector<int>& hBars, vector<int>& vBars) {8 const auto& max_gap = [&](const auto& arr) {9 int result = 1;10 unordered_set<int> lookup(cbegin(arr), cend(arr));11 while (!empty(lookup)) {12 const int x = *begin(lookup);13 int left = x;14 for (; lookup.count(left - 1); --left);15 int right = x;16 for (; lookup.count(right + 1); ++right);17 for (int i = left; i <= right; ++i) {18 lookup.erase(i);19 }20 result = max(result, (right - left + 1) + 1);21 }22 return result;23 };24 25 const int l = min(max_gap(hBars), max_gap(vBars));26 return l * l;27 }28};29 30313233class Solution2 {34public:35 int maximizeSquareHoleArea(int n, int m, vector<int>& hBars, vector<int>& vBars) {36 const auto& max_gap = [&](auto& arr) {37 sort(begin(arr), end(arr));38 int result = 1;39 for (int i = 0, l = 1; i < size(arr); ++i) {40 result = max(result, ++l);41 if (i + 1 < size(arr) && arr[i + 1] != arr[i] + 1) {42 l = 1;43 }44 }45 return result;46 };47 48 const int l = min(max_gap(hBars), max_gap(vBars));49 return l * l;50 }51};52