Ad platform~35 min2s · 256 MBtarget O(n log n) time, O(n) spacegreedy
An ad team has a starting budget and a list of campaigns. A campaign can start only when the budget is at least its cost. When it finishes, the budget grows by the revenue it earned, and the cost is not taken away.
The team runs one campaign at a time, and each campaign can run once. The team wants to reach a revenue target with as few campaigns as possible, and a campaign that unlocks others may be worth running first.
Write fewest_campaigns_to_reach(target, budget, costs, gains).
costs[i] is the budget that campaign i needs before it can start, and gains[i] is the amount it adds to the budget when it finishes.budget, runs campaigns one at a time, and may run each campaign at most once.target. Return 0 if the starting budget already reaches it, and -1 if no sequence of campaigns can.Input: target = 20, budget = 3, costs = [2,5,4,9,12], gains = [3,6,2,10,8]
Output: 3The solution sorts the campaigns by cost. At each step it moves every campaign the budget can start into a heap, and runs the one with the biggest gain.
| Step | Budget | Affordable campaigns (cost, gain) | Run | Budget after |
|---|---|---|---|---|
| 1 | 3 | (2, 3) | gain 3 | 6 |
| 2 | 6 | (5, 6), (4, 2) | gain 6 | 12 |
| 3 | 12 | (4, 2), (9, 10), (12, 8) | gain 10 | 22 |
The budget 22 is at least 20 after 3 campaigns, so the answer is 3.
Input: target = 12, budget = 3, costs = [2,5,4,9,12], gains = [3,6,2,10,8]
Output: 2After the first two campaigns the budget is exactly 12, which meets the target of 12.
Input: target = 100, budget = 3, costs = [2,5,4,9,12], gains = [3,6,2,10,8]
Output: -1Running every campaign adds only 29 to the budget of 3, so 100 can never be reached.
0 ≤ budget ≤ 1,000,000,000 and 0 ≤ target ≤ 100,000,000,000,0001 ≤ len(costs) ≤ 100,000, len(gains) = len(costs), and every cost and gain is between 0 and 1,000,000,000Trying every order of the campaigns costs more than any power of 100,000, and even trying every set costs 2 to the power of 100,000. Each step instead looks at the best affordable campaign, which a heap gives in about 17 steps, so the whole plan costs about 1,700,000 steps. The budget can reach 10^14, which needs 64-bit integers.