Ad platform~25 min2s · 256 MBtarget O(n α(n)) time, O(n) spaceclassic twin: lc-947union-find
An ad screen is a grid, and each banner sits in its own cell, given as a row and a column. A banner can be retired when another banner that is still live shares its row or its column.
Some banners are pinned by a contract and can never be retired. Retiring one banner can change which others may be retired next.
The ad team wants to retire as many banners as possible.
Write most_banners_retired(cells, pinned).
cells[i] is [row, column] for banner i. No two banners share a cell.pinned[i] is 1 when banner i is pinned and 0 otherwise.Input: cells = [[0,0],[0,2],[1,1],[2,1],[2,2],[3,3]], pinned = [0,0,0,0,0,0]
Output: 4The solution joins each banner's row with its column, so banners that share a line end up in one group. It then counts the banners in each group.
| Banner | Row and column joined | Banners in its group |
|---|---|---|
[0,0] |
row 0 and column 0 | 1 |
[0,2] |
row 0 and column 2 | 2 |
[1,1] |
row 1 and column 1 | 1 |
[2,1] |
row 2 and column 1 | 2 |
[2,2] |
row 2 and column 2, which merges both groups | 5 |
[3,3] |
row 3 and column 3 | 1 |
The group of 5 can retire 4 banners and keeps 1. The banner at [3,3] has no neighbour, so it stays. The answer is 4.
Input: cells = [[0,0],[0,2],[1,1],[2,1],[2,2],[3,3]], pinned = [0,0,1,0,1,0]
Output: 3The group of 5 holds 2 pinned banners, and those stay. The other 3 can be retired, one leaf at a time, always next to a banner that is still live.
Input: cells = [[0,0],[0,2],[2,2]], pinned = [0,1,0]
Output: 2The pinned banner at [0,2] shares a row with [0,0] and a column with [2,2]. Both others can go, because the pinned banner stays live.
1 ≤ len(cells) ≤ 100,000, and len(pinned) = len(cells)[row, column] with 0 ≤ row, column ≤ 99,999, all cells are different, and every pinned[i] is 0 or 1Trying every order of retiring costs a number of orders that grows faster than any power of 100,000. Even checking each pair of banners for a shared line costs about 5,000,000,000 pair checks. Each banner can instead be read once, which is 100,000 steps.