Online store~40 min4s · 256 MBtarget O(n^2) time, O(n^2) spacedp · tree-recursion
You work on an online shop. The shop sorts its products into categories that form a tree: a top category, subcategories below it, and so on. Each category has an expected profit for the month, in units, and a profit can be negative when the shelf costs more than the sales.
The homepage can show exactly k categories. A category can appear only if its parent appears too, so shoppers can reach it, and the top category must always appear. Your team lead asks: "Which categories give the largest total profit?" There are up to 3,000 categories.
Write best_featured(parents, profits, k).
profits[v] is the expected profit of category v. Category 0 is the top category.parents[v - 1] is the parent of category v, for every v from 1. Every parent has a smaller number than its child.k categories so that category 0 is chosen, and every chosen category except 0 has its parent chosen.Input: parents = [0, 0, 1, 1, 2], profits = [3, -2, 5, 8, -1, 4], k = 4
Output: 14Category 1 and 2 are below 0, categories 3 and 4 are below 1, and category 5 is below 2. Some choices of 4 categories:
| Chosen categories | Total profit |
|---|---|
| 0, 1, 2, 3 | 3 - 2 + 5 + 8 = 14 |
| 0, 1, 3, 4 | 3 - 2 + 8 - 1 = 8 |
| 0, 2, 5, 1 | 3 + 5 + 4 - 2 = 10 |
The best choice is 0, 1, 2 and 3 with 14. Category 3 earns 8 and sits below category 1, which loses 2.
Input: parents = [0, 0], profits = [-4, 9, 9], k = 1
Output: -4The only category that can appear alone is the top one, even though it loses money.
Input: parents = [0, 1], profits = [1, -2, 3], k = 3
Output: 2When k equals the number of categories, every category appears: 1 - 2 + 3 = 2.
1 ≤ len(profits) ≤ 3,000, and len(parents) = len(profits) - 1.0 ≤ parents[v - 1] < v for every category v from 1.-10,000,000 ≤ profits[v] ≤ 10,000,0001 ≤ k ≤ len(profits)There are up to 2^3000 sets of categories, so no program can try them all. An n × n table has 9 million entries, and an O(n^2) merge of tables is fast enough. The total can reach 3,000 × 10^7 = 3 × 10^10, which does not fit in 32 bits.