Maximum Currency Conversion Rate
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Company: Optiver
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
You are given N currency exchange rate pairs. Each pair is a triple (from_currency, to_currency, rate), meaning that 1 unit of from_currency can be exchanged for rate units of to_currency. All rates are strictly positive real numbers.
Given a source currency and a target currency, find the best (maximum) overall conversion rate achievable by chaining one or more exchanges from source to target. Chaining exchanges multiplies their rates: converting through the sequence A -> B -> C yields an overall rate of rate(A->B) * rate(B->C).
Rules and assumptions:
(A, B, r)
lets you convert
A
to
B
at rate
r
, but does
not
by itself allow converting
B
to
A
. A reverse rate is only available if it appears as its own pair in the input.
(from_currency, to_currency)
appears multiple times, use the one with the highest rate.
source == target
, the answer is
1.0
.
target
is unreachable from
source
, return
-1.0
.
pairs
: a list of
N
triples
[from_currency, to_currency, rate]
, where currencies are strings (e.g.,
"USD"
,
"EUR"
) and
rate
is a positive float.
source
: the starting currency (string).
target
: the desired currency (string).
Return a single float: the maximum achievable conversion rate from source to target, or -1.0 if no conversion path exists. Answers within 1e-6 relative or absolute tolerance are accepted.
pairs = [["USD", "EUR", 0.9],
["EUR", "GBP", 0.85],
["USD", "GBP", 0.7],
["GBP", "JPY", 190.0]]
source = "USD"
target = "JPY"
Output:
145.35
Explanation: the path USD -> EUR -> GBP -> JPY gives 0.9 * 0.85 * 190.0 = 145.35, which beats the direct-ish alternative USD -> GBP -> JPY = 0.7 * 190.0 = 133.0.
1 <= N <= 200
<= 14
0 < rate <= 10.0
1e9
)
source
and
target
are guaranteed to appear in at least one pair