[LeetCode] Maximize Area of Square Hole in Grid

2943. Maximize Area of Square Hole in Grid

There is a grid with n + 2 horizontal bars and m + 2 vertical bars, and initially containing 1 x 1 unit cells.

The bars are 1-indexed.

You are given the two integers, n and m.

You are also given two integer arrays: hBars and vBars.

  • hBars contains distinct horizontal bars in the range [2, n + 1].
  • vBars contains distinct vertical bars in the range [2, m + 1].

You are allowed to remove bars that satisfy any of the following conditions:

  • If it is a horizontal bar, it must correspond to a value in hBars.
  • If it is a vertical bar, it must correspond to a value in vBars.

Return an integer denoting the maximum area of a square-shaped hole in the grid after removing some bars (possibly none).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int maximizeSquareHoleArea(int n, int m, vector<int>& hBars, vector<int>& vBars) {
unordered_map<int, int> h, v;
hBars.push_back(1);
hBars.push_back(n+2);
vBars.push_back(1);
vBars.push_back(m+2);
sort(begin(hBars), end(hBars));
hBars.erase(unique(begin(hBars), end(hBars)), end(hBars));
sort(begin(vBars), end(vBars));
vBars.erase(unique(begin(vBars), end(vBars)), end(vBars));
for(int i = 0; i < hBars.size(); i++) {
int le = max(hBars[i] - 1,1);
for(int j = i, now = hBars[i]; j < hBars.size();j++, now++) {
if(hBars[j] != now) break;
h[hBars[j]-le] += 1;
if(j != hBars.size() - 1) h[hBars[j]-le+1] += 1;
}
}
int res = 4;
for(int i = 0; i < vBars.size(); i++) {
int le = max(vBars[i] - 1, 1);
for(int j = i, now = vBars[i]; j < vBars.size();j ++, now++) {
if(vBars[j] != now) break;
int d1 = vBars[j] - le, d2 = d1 + 1;
if(h.count(d1)) res = max(res, d1 * d1);
if(j != vBars.size() - 1 and h.count(d2)) res = max(res, d2 * d2);
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/26/PS/LeetCode/maximize-area-of-square-hole-in-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.