Maximum Currency Conversion Along a Simple Path
Learn this problemProblem statement
There are currencyCount currencies numbered from 0 through currencyCount - 1. Each directed edge edges[i] = [u, v] permits converting one unit of currency u into rates[i] units of currency v.
For each query queries[j] = [source, target], start with amounts[j] units of the source currency and find the greatest amount of the target currency obtainable along one allowed path.
- A path may visit each currency at most once, including its source and target.
- Multiply the current amount by the rate of every traversed edge. Do not round intermediate amounts.
- Only listed directed conversions exist. Do not automatically add reciprocal edges.
- Stop when the target is reached. When source equals target, the only allowed path is the zero-edge path, returning the starting amount.
- If no allowed path reaches the target, return
-1, even if the starting amount is zero.
Return one floating-point amount per query, in query order. Queries are independent and do not consume or change rates. Profitable cycles may exist, but revisiting a currency is forbidden.
Each returned value is accepted when its absolute error is at most 10^-6 * max(1, abs(expected)).
Function
maximumConversions(currencyCount: int, edges: int[][], rates: double[], queries: int[][], amounts: double[]) → double[]Examples
Example 1
currencyCount = 3edges = [[0,1],[1,2],[0,2]]rates = [2,3,4]queries = [[0,2],[2,0],[1,1]]amounts = [10,10,7]return = [60,-1,7]For 0 to 2, the indirect path 0 → 1 → 2 returns 10 * 2 * 3 = 60, beating the direct result 40. No path goes from 2 to 0. The self-query returns its starting amount 7.
Example 2
currencyCount = 3edges = [[0,1],[1,0],[1,2],[0,2]]rates = [2,2,3,1]queries = [[0,2],[0,0],[1,2]]amounts = [5,5,5]return = [30,5,15]The best path from 0 to 2 is 0 → 1 → 2, yielding 30. Repeating the profitable cycle 0 → 1 → 0 is forbidden. The self-query returns 5, and starting at 1 gives a best target amount of 15.
Constraints
1 <= currencyCount <= 8.0 <= edges.length <= currencyCount * (currencyCount - 1), andrates.length = edges.length.- Every edge has distinct valid endpoints; each directed pair appears at most once.
0.1 <= rates[i] <= 10, with at most three decimal places.0 <= queries.length <= 20, andamounts.length = queries.length.- Every query contains two valid currency indices.
0 <= amounts[j] <= 1000, with at most three decimal places.