Ad platform~30 min2s · 256 MBtarget O(n × D × R) time, O(D × R) spaceclassic twin: lc-474knapsack
An ad platform prepares a campaign. Each ad takes some display units, which is screen time it will occupy, and some review minutes, which is the time a moderator needs to approve it. A campaign has a budget for each.
An ad is shown whole or not at all. The team wants to run as many ads as possible without passing either budget.
Write most_ads_within_budgets(display_costs, review_costs, display_budget, review_budget).
display_costs[i] and review_costs[i] are the display units and the review minutes that ad i needs. A cost can be 0.display_budget and review_budget are the two limits, whole numbers.display_budget and whose review costs add up to at most review_budget.Input: display_costs = [2, 3, 4, 1], review_costs = [3, 1, 2, 2], display_budget = 6, review_budget = 5
Output: 2Let best[d][r] be the most ads that can be chosen from those read so far using at most d display units and at most r review minutes. Start with every cell 0. For each ad, go through the cells with d downwards and r downwards, and set best[d][r] to the larger of its value and best[d - display][r - review] + 1. After the four ads the table is:
| display \ review | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 | 0 | 0 | 1 | 1 | 1 | 1 |
| 2 | 0 | 0 | 1 | 1 | 1 | 1 |
| 3 | 0 | 1 | 1 | 1 | 1 | 2 |
| 4 | 0 | 1 | 1 | 2 | 2 | 2 |
| 5 | 0 | 1 | 1 | 2 | 2 | 2 |
| 6 | 0 | 1 | 1 | 2 | 2 | 2 |
The corner best[6][5] is 2. Two ads fit, for example those with costs (2, 3) and (3, 1), which use 5 display units and 4 review minutes. No three ads fit.
Input: display_costs = [4, 4], review_costs = [1, 1], display_budget = 5, review_budget = 5
Output: 1Each ad fits alone, but together they need 8 display units.
Input: display_costs = [0, 0, 3], review_costs = [0, 0, 3], display_budget = 2, review_budget = 2
Output: 2The two ads that cost nothing fit. The third does not.
1 ≤ len(display_costs) = len(review_costs) ≤ 1000 ≤ display_costs[i], review_costs[i] ≤ 1000 ≤ display_budget, review_budget ≤ 100A table with one cell for each pair of budgets has 101 × 101 = 10,201 cells, and each of the 100 ads updates it once. That is about a million small steps. Trying every choice of ads is 2^100 choices, which no machine can finish.