Ad platform~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-1899greedy
An ad platform lets an advertiser merge campaigns. Every campaign has three caps: a daily spend cap, a daily views cap and a daily clicks cap, all in whole units. Merging a group of campaigns makes one campaign whose cap in each kind is the highest cap of the group.
An advertiser wants one campaign with exact target caps. Your team lead asks: can some group of the campaigns be merged into exactly that target?
Write can_reach_caps(campaigns, target).
campaigns[i] is a list of three numbers: the spend, views and clicks caps of campaign i.target is a list of three numbers: the wanted spend, views and clicks caps.true when some group merges into exactly target, and false otherwise.Input: campaigns = [[2, 5, 3], [1, 8, 4], [1, 7, 5]], target = [2, 7, 5]
Output: trueA group can only raise caps, so a campaign with any cap above the target is useless. Merge all the others, and see what the highest caps are.
| Step | Campaign | Usable? | Best caps so far |
|---|---|---|---|
| [1] | start | [0, 0, 0] |
|
| [2], [3] | [2, 5, 3] |
yes | [2, 5, 3] |
| [2] | [1, 8, 4] |
no, 8 is above 7 | [2, 5, 3] |
| [2], [3] | [1, 7, 5] |
yes | [2, 7, 5] |
| [4] | compare | [2, 7, 5] equals the target |
Input: campaigns = [[3, 4, 5], [4, 5, 6]], target = [3, 2, 5]
Output: falseBoth campaigns have a cap above the target: the views cap 4 is above 2, and the first cap 4 is above 3. No campaign is usable.
Input: campaigns = [[4, 1, 1], [1, 4, 1], [1, 1, 3]], target = [4, 4, 4]
Output: falseAll three campaigns are usable. Their highest caps are 4, 4 and 3, so the clicks cap never reaches 4.
1 ≤ length of campaigns ≤ 100000, and every campaign has exactly three caps1 to 1000000target has exactly three valuesThere are 2^100000 groups of 100,000 campaigns, so trying every group is out of the question. Even a group of three can be chosen in about 10^14 ways.
The problem has a shortcut. A campaign above the target in any cap can never be in a good group, and merging all the others gives the highest caps you can reach. One pass is enough.