Best Conversion Product Over Simple Currency Paths
Trees & GraphsAuto-graded · 17 test casesLast updated
Find the largest product of edge weights over simple directed paths between two nodes, using backtracking DFS, with a special case for identical endpoints and an unreachable case.
Best Conversion Product Over Simple Currency Paths
A currency market has num_currencies currencies, labeled 0 to num_currencies - 1. Some ordered pairs have a direct conversion offer, given as a triple [u, v, r]. Converting 1 unit of currency u yields exactly r units of currency v. Offers work in one direction only. An offer from u to v does not give you an offer from v to u.
You can chain offers. If you convert u -> v at rate r1 and then v -> w at rate r2, the combined rate for that route is r1 * r2.
A route must be simple: it may not visit the same currency twice. This keeps the best result finite even when the offers contain profitable cycles.
You start with 1 unit of currency start and want as much of currency target as possible.
Task
Return the largest combined rate over all simple routes from start to target.
- If
start == target, return1.0. The empty route is the only simple route, and no cycle may be used. - If no route leads from
starttotarget, return-1.0. - The same ordered pair may appear in several offers with different rates. Any of them may be used, so the best one for that step is the one that gives the best overall product.
- A route that ends up with less than 1 unit still counts. Return the maximum product even if it is below 1.
Function
Implement max_exchange_rate(num_currencies, rates, start, target), where:
num_currenciesis the number of currencies.ratesis a list of[u, v, r]offers.startandtargetare the starting and ending currencies.
It returns a float: the best achievable amount of target, or -1.0 if unreachable.
Constraints
1 <= num_currencies, small enough that exploring all simple routes is feasible (around 15 or fewer).0 <= len(rates); duplicate pairs and self-loops (u == v) may appear. Self-loops can never be part of a simple route.0 <= u, v, start, target < num_currencies.- Every rate
ris a positive real number. - Results are compared as floating point numbers, so tiny rounding differences are acceptable.
Examples
Example 1
Input: max_exchange_rate(3, [[0, 1, 2], [1, 2, 3], [0, 2, 4]], 0, 2)
Output: 6
Hints
Hint 1
Because routes may not repeat a currency, the best route is the maximum over a finite set of simple paths. Think about enumerating them.
Hint 2
Run a depth-first search from the start while carrying the product so far, and track which currencies are on the current route. Un-mark a currency when you backtrack so other routes can use it.
Hint 3
Handle start == target before searching (answer 1.0), and use a sentinel such as None to tell 'no route found' apart from a legitimately small product.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since a route may not repeat a currency, the answer is the maximum product over a finite set of simple paths from start to target. Longest-path and maximum-product problems with a "no repeated node" rule do not have a simple shortest-path-style algorithm. Profitable cycles would break Bellman-Ford style relaxation, so we enumerate the simple paths directly with backtracking.
- If
start == target, return1.0immediately. The only simple route is the empty one. - Build an adjacency list from the offers. Parallel offers stay as separate entries, so each is tried.
- Run a depth-first search from
start, carrying the product of rates so far and a boolean array marking currencies on the current route. - When the search reaches
target, compare the product to the best seen so far and stop extending that route. Extending pasttargetwould visit it twice. - For each outgoing offer to an unmarked currency, mark it, recurse with the updated product, then unmark it (backtrack).
- If no route reached
target, return-1.0. Otherwise return the best product. ANonesentinel distinguishes "nothing found" from a small valid product.
Why it is correct
The DFS with marking and unmarking visits every simple path from start exactly once per distinct sequence of offers. Every simple route to target is therefore evaluated, and its product is computed as the product of its rates. Taking the maximum gives the required answer. Stopping at target is valid because any longer route through target would repeat it.
Complexity
- Time: exponential in the worst case, O(number of simple paths times path length), roughly O(n!) for dense graphs. This is acceptable for the small graphs in this problem.
- Space: O(n + m) for the graph, plus O(n) recursion depth and marking array.
Reference solution
from typing import List
def max_exchange_rate(num_currencies: int, rates: List[List[float]], start: int, target: int) -> float:
if start == target:
return 1.0
graph = [[] for _ in range(num_currencies)]
for u, v, rate in rates:
graph[int(u)].append((int(v), rate))
best = None
on_path = [False] * num_currencies
on_path[start] = True
def dfs(node, product):
nonlocal best
if node == target:
if best is None or product > best:
best = product
return
for nxt, rate in graph[node]:
if not on_path[nxt]:
on_path[nxt] = True
dfs(nxt, product * rate)
on_path[nxt] = False
dfs(start, 1.0)
return -1.0 if best is None else best