KatInterview

Finding Profitable Exchange Cycles with Transaction Fees

Trees & GraphsModel answer
MediumModel answerTrees & Graphsgraph-algorithmsbellman-fordnegative-cycle

Last updated

Given exchange rates between currencies and a per-cycle transaction cost, determine if any sequence of trades can yield a profit.

You're analyzing currency markets to find trading opportunities. You have access to a K×K matrix of exchange rates where entry rates[i][j] represents how much of currency j you receive for one unit of currency i. The diagonal entries satisfy rates[i][i] = 1.

When you complete a full cycle of trades (starting and ending with the same currency), you pay a transaction fee equal to 0.01% of your initial amount.

Write a function that determines whether any sequence of currency exchanges exists that would leave you with strictly more money than you started with, after accounting for the transaction fee.

Input:

  • rates: a K×K matrix of positive floats representing exchange rates

Output:

  • True if a profitable trading cycle exists, False otherwise

Example:

rates = [
    [1.0, 0.9, 1.5],
    [1.1, 1.0, 0.8],
    [0.7, 1.2, 1.0]
]
# Currency 0 → 1 → 2 → 0 gives: 0.9 × 1.2 × 0.7 = 0.756 (loss)
# Currency 0 → 2 → 1 → 0 gives: 1.5 × 1.2 × 1.1 = 1.98 (profit even after 0.01% fee)
# Returns True

Constraints:

  • 1 ≤ K ≤ 200
  • All rates are positive floats
  • The fee applies once per completed cycle, not per individual trade

Hints

Hint 1

Consider what happens if you find a cycle with any profit at all—could you exploit it multiple times within a single 'round trip'?

Hint 2

Converting exchange rates to logarithms transforms products into sums, making this a classic graph problem.

Hint 3

This problem reduces to finding a specific type of cycle in a weighted directed graph.