Problem · Graph
Maximum Currency Conversion with Arbitrage
Learn this problemProblem statement
Each directed conversion edge i means that one unit of sources[i] converts to rates[i] units of targets[i]. Edges are directed; no reverse conversion exists unless it is listed.
Starting with amount units of source, return the maximum amount of target obtainable by applying edges any number of times.
- Return
-1.0whentargetis unreachable fromsource. - Return
-2.0when a multiplicative-gain cycle is reachable fromsourceand can still reachtarget, so the obtainable amount is unbounded. - Otherwise return the finite maximum amount. Using zero edges is allowed, so converting a currency to itself returns
amountunless an applicable gain cycle makes it unbounded.
Function
maximumConversion(sources: String[], targets: String[], rates: double[], source: String, target: String, amount: double) → doubleExamples
Example 1
sources = ["USD","CAD","USD","GBP"]targets = ["CAD","JPY","GBP","JPY"]rates = [1.3,100.0,0.8,150.0]source = "USD"target = "JPY"amount = 10.0return = 1300.0The USD-CAD-JPY route multiplies by 130, producing 1300. The USD-GBP-JPY route multiplies by 120.
Example 2
sources = ["A","B","B"]targets = ["B","A","C"]rates = [2.0,0.6,1.0]source = "A"target = "C"amount = 1.0return = -2.0The cycle A-B-A multiplies the amount by 1.2. It is reachable from A and can exit through B-C, so the target amount is unbounded.
Example 3
sources = ["A"]targets = ["B"]rates = [2.0]source = "B"target = "A"amount = 5.0return = -1.0The only edge points from A to B, so A is unreachable from B.
Constraints
0 <= sources.length == targets.length == rates.length <= 5000- There are at most
300distinct currency codes across the edges and query. - Each currency code contains
1to10uppercase English letters. 0 < rates[i] <= 1000000and0 < amount <= 1000000000.- Any directed cycle's product is either at most
1or differs from1by at least10^-9. - Every finite answer is representable by a
double.