Ad platform~30 min2s · 256 MBtarget O(n^2 log v) time, O(n^2) spaceclassic twin: lc-547dfs · binary-search-answer
An ad planner has n campaigns. A matrix gives the audience overlap of every pair, in parts per million. The matrix is symmetric, and the diagonal is ignored.
For a threshold t, two campaigns are linked when their overlap is at least t. Campaigns that are linked, directly or through a chain, form one cluster. The planner wants as few clusters as the budget allows, with links that are as strong as possible.
Write best_threshold(overlap, k).
overlap[i][j] is the overlap of campaigns i and j, from 0 to 1,000,000, with overlap[i][j] = overlap[j][i].k is the largest number of clusters allowed.t from 0 to 1,000,000 for which the campaigns form at most k clusters.Input: overlap = [[1000000,900,300,100,200],[900,1000000,700,150,120],[300,700,1000000,400,250],[100,150,400,1000000,800],[200,120,250,800,1000000]], k = 2
Output: 700The number of clusters changes only at an overlap value in the matrix, so the search works on those values. A higher threshold links fewer pairs, so the number of clusters never falls as t rises. A binary search over the sorted values finds the last one with at most 2 clusters.
| Low | High | Middle value | Clusters | Decision |
|---|---|---|---|---|
| 0 | 1000000 | 300 | 1 | keep, go higher |
| 300 | 1000000 | 800 | 3 | too many, go lower |
| 300 | 700 | 400 | 1 | keep, go higher |
| 400 | 700 | 700 | 2 | keep, go higher |
The search ends at 700. At 800 the campaigns split into 3 clusters.
Input: overlap = [[1000000,500,500],[500,1000000,500],[500,500,1000000]], k = 2
Output: 500Every pair has overlap 500. At 500 there is 1 cluster, and at 501 there are 3. Two clusters never occur, but at most two is allowed.
Input: overlap = [[7]], k = 1
Output: 1000000One campaign is always one cluster, so the largest threshold works.
1 ≤ n ≤ 300, and overlap is an n × n matrix with values from 0 to 1,000,0001 ≤ k ≤ 301The matrix has up to 300 × 300 = 90,000 cells and about 45,000 different values. Trying every value from the top, each with its own walk over the matrix, costs about 45,000 × 90,000 = 4 × 10^9 steps. The cluster count only grows with the threshold, so a binary search needs about 16 walks, about 1.5 × 10^6 steps.