Maps app~15 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-112tree-recursion
A maps app plans a delivery trip that starts at a depot. At every junction the road splits into at most two onward roads, a left one and a right one. A junction with no onward road is a dead end, where the trip stops.
Every junction has a toll. Some tolls are negative: they are discounts. Your team lead asks whether some trip from the depot to a dead end costs exactly the driver's budget.
Write has_exact_route(values, left, right, budget).
0 to n - 1, and junction 0 is the depot. An empty network has three empty lists.values[i] is the toll at junction i. left[i] and right[i] are the numbers of the onward junctions, or -1 where there is none.0, follows onward roads, and stops at a dead end. Its cost is the sum of the tolls of every junction on it, including the depot and the dead end.true when some trip costs exactly budget. Return false otherwise.Input: values = [7, 3, 9, 4, 6, 2], left = [1, 3, -1, -1, -1, -1], right = [2, 4, 5, -1, -1, -1], budget = 16
Output: trueJunction 0 (toll 7) leads to 1 and 2. Junction 1 (toll 3) leads to 3 (toll 4) and 4 (toll 6). Junction 2 (toll 9) leads to 5 (toll 2).
Hand the unspent budget down from the depot, and pay each toll as you arrive. The left side is tried first.
| Junction | Budget before the toll | Toll | Budget after | What happens |
|---|---|---|---|---|
0 |
16 | 7 | 9 | not a dead end: go on |
1 |
9 | 3 | 6 | not a dead end: go on |
3 |
6 | 4 | 2 | dead end with 2 left: this trip fails |
4 |
6 | 6 | 0 | dead end with nothing left: found |
The trip 0, 1, 4 costs 7 + 3 + 6 = 16.
Input: values = [5, 4], left = [1, -1], right = [-1, -1], budget = 5
Output: falseThe only trip goes from junction 0 to the dead end at junction 1, and costs 5 + 4 = 9. Junction 0 costs 5 but is not a dead end.
Input: values = [], left = [], right = [], budget = 0
Output: falseAn empty network has no trip at all, even for a budget of 0.
0 ≤ length of values = length of left = length of right ≤ 10^5-1000 ≤ values[i] ≤ 1000left and right is -1 or a junction number from 1 to n - 10-10^9 ≤ budget ≤ 10^9A network can be one long road of 100,000 junctions. Writing out the whole trip so far at every junction costs about n^2 / 2 steps on it. Calls that wait for each other would be 100,000 deep, which is more than Python allows by default.
Hand down only the running total, one number, and keep the waiting junctions in a list.