Parcel-delivery app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-337tree-recursion · dp
A freight app runs a network of depots. Depot 0 is the hub. Every depot sends goods on to at most two sub-depots, a left one and a right one, so the network is a tree.
Each depot has parcels waiting. A courier van can empty a depot and its sub-depot on the same day only if two docks are free, and the network has one dock per link. So a depot and a depot directly linked to it are never both emptied. Your team lead asks: what is the most parcels one day of collecting can bring in?
Write most_parcels(parcels, left, right).
0 to n - 1, and depot 0 is the hub. There is at least one depot.parcels[i] is the number of parcels waiting at depot i. left[i] and right[i] are the sub-depots of depot i, or -1 where there is none.Input: parcels = [4, 6, 3, 5, 1, 9, 2], left = [1, 3, 5, -1, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1]
Output: 21The hub 0 sends goods to depots 1 and 2. Depot 1 sends on to 3 and 4. Depot 2 sends on to 5 and 6.
Work from the bottom up. Every depot has two numbers: the best total in its part of the network when the depot is emptied (empty), and when it is not (alone). Emptying a depot adds its parcels and the alone total of each sub-depot. Leaving it alone adds the better of the two totals of each sub-depot.
| Depot | Parcels | empty |
alone |
|---|---|---|---|
6 |
2 | 2 | 0 |
5 |
9 | 9 | 0 |
4 |
1 | 1 | 0 |
3 |
5 | 5 | 0 |
2 |
3 | 3 | 11 |
1 |
6 | 6 | 6 |
0 |
4 | 21 | 17 |
The best choice empties the hub and the four leaf depots: 4 + 5 + 1 + 9 + 2 = 21.
Input: parcels = [3, 8], left = [1, -1], right = [-1, -1]
Output: 8The two depots are linked, so only one can be emptied. The better one has 8 parcels.
Input: parcels = [9], left = [-1], right = [-1]
Output: 9One depot, and nothing links to it.
1 ≤ length of parcels = length of left = length of right ≤ 10^50 ≤ parcels[i] ≤ 1000left and right is -1 or a depot number from 1 to n - 10There are up to 2^100000 sets of depots, so trying every set is out of the question. Even a search that repeats work along a long chain of depots becomes far too slow.
A chain of 100,000 depots also makes nested calls 100,000 deep, more than Python allows by default. The total is at most 10^8, so a 32-bit integer holds it. Handle each depot once, from the bottom up, with a loop.