Best Net Reward Route to an Underscore Node in a DAG
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the highest net score of a route in a weighted DAG that ends at a node whose name starts with an underscore, using topological order and DP.
You are given a directed acyclic graph of locations. Each location has a name and a reward for visiting it. Each directed route between two locations has a travel cost.
Starting at a given source location, you walk along routes and stop at a target location. A location is a target if its name begins with the character _. Find the best achievable net score.
Scoring a walk
For a walk that starts at source and follows routes source = v0 -> v1 -> ... -> vk:
- You collect the reward of each location you arrive at, namely
v1 ... vk. - The source's reward is treated as
0, whatever value is listed for it. - You pay the cost of every route you use.
net score = (rewards of v1..vk) - (costs of the k routes used)
Rules
- A walk with zero routes is allowed. It ends at the source and scores
0. It is valid only if the source's name begins with_. - A walk may pass through target locations and keep going. Every target reachable from the source is a candidate end point, not only targets with no outgoing routes.
- A location that appears in
routesbut not innode_rewardshas reward0. - Rewards and costs may be negative or zero. The best score can be negative, and you must still return it.
- Several routes may connect the same pair of locations. Any of them may be used.
- Only locations reachable from
sourcematter.
Task
Implement the function. It takes:
node_rewards: a dictionary mapping location name to its integer reward.routes: a list of[from_name, to_name, cost]entries, one per directed route.source: the name of the starting location.
Return the maximum net score over all walks from source that end at a target location. If no target location is reachable from source, return None.
The graph is guaranteed to have no directed cycles.
Constraints
- The graph is a DAG, so it contains no directed cycles.
- Names are non-empty strings.
- Rewards and costs are integers and may be negative.
- The number of locations and routes is small enough that an
O(V + E)solution is comfortably fast. sourcemay or may not appear as a key innode_rewards. Its listed reward, if any, is ignored.
Examples
Example 1
Input: best_route_value({'start': 0, 'a': 5, '_end': 10}, [['start', 'a', 2], ['a', '_end', 3]], 'start')
Output: 10
Example 2
Input: best_route_value({'start': 0, 'a': 4, 'b': 12, '_slow': 1, '_fast': 7}, [['start', 'a', 1], ['a', '_slow', 1], ['start', 'b', 5], ['b', '_fast', 2]], 'start')
Output: 12
Example 3
Input: best_route_value({'start': 0, '_done': -3}, [['start', '_done', 5]], 'start')
Output: -8
Hints
Hint 1
Because the graph has no cycles, you can order the locations so that every route goes from an earlier location to a later one. Think about what that lets you compute in a single pass.
Hint 2
Keep, for each location, the best net score of any walk from the source to it, using negative infinity for locations you cannot reach. When you take a route u -> v with cost c, the candidate for v is best[u] - c + reward(v).
Hint 3
Do not seed unreachable locations with 0, since that invents walks that never started at the source. At the end, take the maximum only over reachable locations whose names start with an underscore, and return None if there are none.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a longest-path problem on a DAG, which is easy because the graph has a topological order. If we process locations in that order, every predecessor of a location is finished before the location itself, so one DP pass is enough.
- Collect locations and build the graph. Gather every name from
node_rewards, thesource, and both ends of every route. Build adjacency lists and in-degree counts. - Topological sort. Use Kahn's algorithm: start with all in-degree-0 locations, pop one, and decrement the in-degrees of its neighbours, queueing any that reach 0.
- DP over that order. Let
best[v]be the highest net score of a walk fromsourcetov. Initialise every location to negative infinity (unreachable) andbest[source] = 0. For each locationuin topological order, skip it ifbest[u]is still negative infinity. Otherwise, for each routeu -> vwith costc, updatebest[v] = max(best[v], best[u] - c + reward(v)). - Answer. Take the maximum
bestover reachable locations whose name starts with_. If there are none, returnNone.
Why it is correct
Any walk to v ends with some route u -> v. In topological order u comes before v, so when we relax u's outgoing routes, best[u] already accounts for every walk into u. By induction along the order, best[v] is the maximum over all incoming routes of best[u] - c + reward(v), which is exactly the best walk score to v.
Several details matter:
- Negative rewards and costs are fine, because the DP never assumes non-negative weights (unlike Dijkstra).
- Using negative infinity for unreachable locations stops walks from "starting" anywhere other than the source.
- The source's own reward is never added, because rewards are only collected on arrival, and
best[source]starts at 0. If the source's name starts with_, the empty walk gives candidate score 0. - Targets need not be sinks. A walk can go through one target to a better one, so we maximise over all reachable targets.
- Locations missing from
node_rewardsget reward 0 via.get(v, 0). - Parallel routes are all relaxed, so the best one wins naturally.
Complexity
- Time:
O(V + E). - Space:
O(V + E)for adjacency lists, in-degrees, the order, andbest.
Reference solution
from collections import deque
from typing import Dict, List, Optional
def best_route_value(node_rewards: Dict[str, int], routes: List[List], source: str) -> Optional[int]:
names = set(node_rewards)
names.add(source)
adjacency = {n: [] for n in names}
in_degree = {n: 0 for n in names}
for u, v, cost in routes:
names.add(u)
names.add(v)
adjacency.setdefault(u, []).append((v, cost))
adjacency.setdefault(v, [])
in_degree.setdefault(u, 0)
in_degree.setdefault(v, 0)
in_degree[v] += 1
# Kahn's algorithm for a topological order.
queue = deque(n for n in names if in_degree[n] == 0)
topo = []
while queue:
u = queue.popleft()
topo.append(u)
for v, _ in adjacency[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
NEG = float("-inf")
best = {n: NEG for n in names}
best[source] = 0
for u in topo:
if best[u] == NEG:
continue
for v, cost in adjacency[u]:
cand = best[u] - cost + node_rewards.get(v, 0)
if cand > best[v]:
best[v] = cand
finals = [best[n] for n in names if n.startswith("_") and best[n] != NEG]
return max(finals) if finals else None