Best Multi-Hop Exchange Rate Between Two Currencies
Trees & GraphsAuto-graded · 15 test casesLast updated
Find the largest product of directed exchange rates along any path between two currencies, using Bellman-Ford-style relaxation on a graph that may contain cycles and rates above 1.
Best Multi-Hop Exchange Rate
A currency exchange publishes a list of directed conversion rates. Each entry is a triple [from, to, rate], meaning one unit of from can be converted into rate units of to. Converting along several consecutive entries multiplies their rates together.
Write a function that returns the largest total conversion factor obtainable when going from a starting currency to a destination currency, using any sequence of the given entries.
Rules
- Entries are directed. An entry
["USD", "EUR", 0.9]does not let you convert EUR back to USD, and you must not infer a reverse rate. - The value of a path is the product of the rates of its entries. Return the maximum over all paths from the start currency to the destination currency.
- If the start and destination currency are the same, return
1.0, even if that currency does not appear in any entry. - If the destination cannot be reached from the start (including when either currency never appears in the entries, or
ratesis empty), return0.0. - There may be several entries between the same ordered pair of currencies. Any of them may be used, so the best one counts.
- Rates can be smaller or larger than 1.
- The graph may contain cycles, but no cycle has a product greater than 1. Looping back through a currency never improves the result.
- Return a floating-point number. Tiny rounding differences are natural, so multiply the rates along the path as given.
Function
Implement best_exchange_rate(from_currency, to_currency, rates):
from_currency: string, the starting currency.to_currency: string, the destination currency.rates: list of[from, to, rate]entries, with string currencies and a positive float rate.- Returns: the maximum achievable product as a float,
1.0if the two currencies are equal, or0.0if unreachable.
Constraints
- Every rate is a positive number.
- No cycle in the graph has a rate product strictly greater than 1.
- The number of distinct currencies and entries is small enough for an
O(V * E)solution. - Currency names are case-sensitive strings.
Examples
Example 1
Input: best_exchange_rate('USD', 'GBP', [['USD', 'EUR', 0.9], ['EUR', 'GBP', 0.8]])
Output: 0.7200000000000001
Hints
Hint 1
Model each currency as a node and each entry as a directed edge. The value of a path is the product of its edge rates, and you want the maximum product.
Hint 2
Plain Dijkstra on products only works when every rate is at most 1. Rates above 1 behave like negative weights in log space, so use a Bellman-Ford style relaxation: best[to] = max(best[to], best[from] * rate).
Hint 3
Because no cycle is profitable, an optimal path never repeats a currency, so at most V-1 rounds of relaxation are needed. Stop early when a round changes nothing, and handle the equal-currency case separately.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each currency as a node and each entry as a directed edge whose weight is its rate. The value of a path is the product of its edge weights, and we want the maximum product from the start to the destination.
A Dijkstra-style greedy search is only safe when extending a path can never increase its value, which requires every rate to be at most 1. Here rates can exceed 1, which corresponds to a negative weight under -log(rate), so Dijkstra can give wrong answers. The guarantee that no cycle has a product above 1 means there is no negative cycle in log space, which is exactly the precondition for Bellman-Ford. We run it directly on products:
- If the two currencies are equal, return
1.0. - Keep
best[c], the best known product from the start to currencyc, beginning withbest[start] = 1.0. - Repeat up to
V - 1rounds (V is the number of distinct currencies). In each round, for every entry(s, t, r)withsalready reached, trybest[t] = max(best[t], best[s] * r). Updates are written to a copy so each round extends paths by at most one more edge. - Stop early if a round changes nothing.
- Return
best[destination], or0.0if it was never reached.
Why it is correct
Since no cycle has a product greater than 1, going around a cycle never helps, so some optimal path uses no repeated currency and therefore at most V - 1 edges. After k rounds, best[v] is at least the best product over all paths with at most k edges, so V - 1 rounds suffice. Unreached currencies are never in best, which yields 0.0 for unreachable targets. Parallel edges are handled automatically because the maximum is taken.
Complexity
- Time:
O(V * E)worst case, often much less because of early termination. - Space:
O(V).
Reference solution
from typing import List
def best_exchange_rate(from_currency: str, to_currency: str, rates: List[List]) -> float:
if from_currency == to_currency:
return 1.0
best = {from_currency: 1.0}
currencies = {from_currency, to_currency}
for source, target, rate in rates:
currencies.add(source)
currencies.add(target)
# With no profitable cycle, an optimal path can be chosen without repeated currencies,
# so at most len(currencies) - 1 rounds of relaxation are required.
for _ in range(len(currencies) - 1):
updated = best.copy()
changed = False
for source, target, rate in rates:
if source in best:
value = best[source] * rate
if value > updated.get(target, 0.0):
updated[target] = value
changed = True
best = updated
if not changed:
break
return best.get(to_currency, 0.0)