You start with 1.0 unit of initial_currency. Exchange rates are given for two consecutive days.
On day 1, each pair pairs1[i] = [start_i, target_i] lets you convert start_i into target_i at rate rates1[i], so one unit of start_i becomes rates1[i] units of target_i. You can also convert target_i back into start_i at rate 1 / rates1[i]. Day 2 works the same way with pairs2 and rates2.
You may make any number of conversions on day 1 (including none) using only day 1 rates, followed by any number of conversions on day 2 (including none) using only day 2 rates. Return the largest amount of initial_currency you can hold at the end of day 2.
Function Signature
def max_amount(
initial_currency: str,
pairs1: list[list[str]],
rates1: list[float],
pairs2: list[list[str]],
rates2: list[float],
) -> float:
Rules
-
Every day 1 conversion happens before every day 2 conversion, and a rate can only be used on its own day, in either direction.
-
The result is a float. A value within
10−5
relative or absolute error of the exact answer counts as correct.
Constraints
-
1 <= len(initial_currency) <= 3
, and
initial_currency
has only uppercase English letters.
-
1 <= len(pairs1) == len(rates1) <= 10
-
1 <= len(pairs2) == len(rates2) <= 10
-
Each pair is
[start, target]
, and every currency name has 1 to 3 uppercase English letters.
-
1.0 <= rates1[i], rates2[i] <= 10.0
-
Neither day's conversion graph has contradictions or cycles.
-
The answer is at most
5 * 10^10
.
Examples
Input: initial_currency = "EUR", pairs1 = [["EUR", "USD"], ["USD", "JPY"]], rates1 = [2.0, 3.0], pairs2 = [["JPY", "USD"], ["USD", "CHF"], ["CHF", "EUR"]], rates2 = [4.0, 5.0, 6.0]
Output: 720.0
On day 1, EUR to USD to JPY turns 1.0 EUR into 1 * 2 * 3 = 6 JPY. On day 2, JPY to USD to CHF to EUR turns that into 6 * 4 * 5 * 6 = 720 EUR, and no other route ends with more.
Input: initial_currency = "NGN", pairs1 = [["NGN", "EUR"]], rates1 = [9.0], pairs2 = [["NGN", "EUR"]], rates2 = [6.0]
Output: 1.5
Day 1 turns 1.0 NGN into 9 EUR. On day 2 the pair NGN to EUR at rate 6 can be used in reverse, so 9 EUR becomes 9 / 6 = 1.5 NGN, which beats keeping the original 1.0 NGN.
Input: initial_currency = "USD", pairs1 = [["USD", "EUR"], ["EUR", "GBP"]], rates1 = [2.0, 1.5], pairs2 = [["USD", "EUR"]], rates2 = [4.0]
Output: 1.0
After day 1 you could hold 2 EUR or 3 GBP. Day 2 has no GBP rate, and 2 EUR only buys back 2 / 4 = 0.5 USD, so making no conversions and keeping 1.0 USD is best.