Monitoring~30 min2s · 256 MBtarget O(m n log(min(m, n))) time, O(m n) spaceclassic twin: lc-1292binary-search-answer · prefix-sums
A monitoring system divides a data centre floor into a grid of racks. For each rack, the system counts the alerts raised today. No rack has a negative count.
An engineer wants the largest square block of neighbouring racks, k rows by k columns, whose alerts add up to at most a limit. That block is the biggest area that is still quiet enough. How large can k be?
Write largest_square(alerts, limit).
alerts[r][c] is the number of alerts for the rack in row r and column c.k consecutive rows by k consecutive columns. Its total is the sum of the alerts of its k × k racks.k for which some square block has a total of at most limit. Return 0 if even a single rack is above the limit.Input: alerts = [[2, 1, 0, 4], [1, 0, 3, 1], [0, 2, 1, 2], [5, 1, 0, 1]], limit = 6
Output: 2A smaller square inside a square never has a larger total, because no count is negative. So if a side k works, every smaller side works too. Search the side in the window [lo, hi), which starts as [1, 5). For a side, check every square of that side with prefix sums.
| Step | lo | hi | mid | smallest square total of side mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 5 | 3 | 10 | 10 > 6, so no square works, hi = 3 |
| 2 | 1 | 3 | 2 | 3 | 3 <= 6, a square works, lo = 3 |
| end | 3 | 3 | the first side that fails is 3, so the answer is 2 |
The best 2 × 2 block is the one at rows 1 to 2 and columns 0 to 1, with the counts 1, 0, 0 and 2, total 3.
Input: alerts = [[9]], limit = 5
Output: 0One rack above the limit: no square works, so the answer is 0.
Input: alerts = [[1, 1], [1, 1]], limit = 4
Output: 2The whole grid has a total of exactly 4, which equals the limit, so a 2 × 2 block works. The answer is 2, the largest possible side.
alerts is a grid of m rows and n columns, with 1 ≤ m, n ≤ 3000 ≤ alerts[r][c] ≤ 1,000, so no cell is negative0 ≤ limit ≤ 1,000,000,000Adding up the cells of every square of every side costs about m × n × k² steps for each side k, which is far beyond the limit. With prefix sums, one square total costs 4 lookups, and checking all the squares of one side costs about m × n steps. A binary search over the side, up to 300, needs about 9 checks, so about 8 × 10^5 steps.