You are given n currencies labeled from 0 to n - 1 and a list of directed exchange rates. Determine whether there exists an arbitrage opportunity.
An arbitrage opportunity exists when you can start with some amount of a currency, perform a series of exchanges through other currencies, and end up with more of the original currency than you started with.
Each exchange rate is represented as [from, to, rate], meaning you can exchange 1 unit of currency from for rate units of currency to.
Return True if an arbitrage opportunity exists, otherwise return False.
Function Signature
def has_arbitrage(n: int, rates: list[list[float]]) -> bool:
Rules
-
In each entry of
rates
,
from
and
to
are integer currency indices and
rate
is a positive number.
-
Rates are directed. Exchanging
b
back into
a
is possible only if
rates
also has an entry from
b
to
a
.
-
An opportunity must end in the currency it started from, and the product of the rates along the way must be strictly greater than 1. A cycle whose product is exactly 1 does not count.
-
A cycle may start at any currency and pass through any number of other currencies.
-
The tests avoid floating-point borderline cases: for every cycle, the product of its rates is either at most 1 or at least 1.000001.
Constraints
-
2 <= n <= 500
-
1 <= len(rates) <= n * (n - 1)
-
0 <= rates[i][0], rates[i][1] < n
-
rates[i][0] != rates[i][1]
-
0.001 <= rates[i][2] <= 1000.0
-
All
(from, to)
pairs are unique.
Examples
Input: n = 3, rates = [[0, 1, 1.2], [1, 2, 1.3], [2, 0, 0.9]]
Output: True
Starting with 1 unit of currency 0 and exchanging along 0 -> 1 -> 2 -> 0 gives 1 × 1.2 × 1.3 × 0.9 = 1.404 units of currency 0, which is more than the starting amount.
Input: n = 3, rates = [[0, 1, 0.5], [1, 2, 0.5], [2, 0, 0.5]]
Output: False
The only cycle is 0 -> 1 -> 2 -> 0, and its product is 0.5 × 0.5 × 0.5 = 0.125, so every trip around it loses money.
Input: n = 3, rates = [[0, 1, 2.0], [1, 0, 0.5], [1, 2, 3.0]]
Output: False
The round trip 0 -> 1 -> 0 returns exactly 2.0 × 0.5 = 1 unit, which is not more than the starting amount. The exchange from 1 to 2 triples the amount, but no rate leads out of currency 2, so that money never returns to the currency it started in.