Maximize Amount After Two Days of Conversions - Problem
Imagine you're a currency trader with a unique opportunity: you have access to different exchange rates on two consecutive trading days, and you want to maximize your profit!
You start with 1.0 unit of your initial currency. On Day 1, you can make any number of currency conversions using the rates from pairs1 and rates1. On Day 2, you can make additional conversions using pairs2 and rates2.
Key Rules:
- Each conversion is bidirectional: if you can convert A→B at rate
r, you can also convert B→A at rate1/r - You can make zero or more conversions each day
- Your goal is to end up with the maximum possible amount of your initial currency
Example: Start with 1.0 USD, convert USD→EUR at 0.85, then EUR→GBP at 1.2, then on day 2 convert GBP→USD at 1.3. Final amount: 1.0 × 0.85 × 1.2 × 1.3 = 1.326 USD
Input & Output
example_1.py — Basic Currency Exchange
$
Input:
initialCurrency = "EUR", pairs1 = [["EUR","USD"], ["USD","JPY"]], rates1 = [2.0, 3.0], pairs2 = [["JPY","USD"], ["USD","EUR"]], rates2 = [4.0, 5.0]
›
Output:
20.0
💡 Note:
Day 1: Start with 1.0 EUR → convert to USD (1.0 × 2.0 = 2.0) → convert to JPY (2.0 × 3.0 = 6.0). Day 2: Convert JPY to USD (6.0 × 4.0 = 24.0) → convert to EUR (24.0 × 5.0 = 120.0). But wait, we can also convert back: JPY→USD at 4.0, USD→EUR at 5.0 gives us 6.0 × 4.0 × 5.0 = 120.0. However, the optimal path is EUR→USD→JPY on day 1 (getting 6.0 JPY), then JPY→USD on day 2 (getting 24.0 USD), but we need EUR back, so USD→EUR gives us 24.0/5.0 = 4.8. Actually, JPY→USD→EUR gives us 6.0 × 4.0 / 5.0 = 4.8. The maximum we can achieve is 20.0 EUR.
example_2.py — No Conversion Optimal
$
Input:
initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [0.8], pairs2 = [["EUR","USD"]], rates2 = [1.1]
›
Output:
1.0
💡 Note:
Day 1: We can convert USD→EUR at 0.8 (getting 0.8 EUR) or stay with USD (1.0). Day 2: If we have 0.8 EUR, we can convert back to USD at 0.8 × 1.1 = 0.88 USD. Since 1.0 > 0.88, the optimal strategy is to make no conversions and keep the original 1.0 USD.
example_3.py — Multiple Currency Chain
$
Input:
initialCurrency = "USD", pairs1 = [["USD","EUR"], ["EUR","GBP"]], rates1 = [0.85, 1.2], pairs2 = [["GBP","USD"]], rates2 = [1.3]
›
Output:
1.326
💡 Note:
Day 1: USD→EUR→GBP gives us 1.0 × 0.85 × 1.2 = 1.02 GBP. Day 2: Convert GBP→USD gives us 1.02 × 1.3 = 1.326 USD. This is better than staying in USD (1.0) or just converting USD→EUR and back.
Constraints
- 1 ≤ pairs1.length, pairs2.length ≤ 10
- rates1.length == pairs1.length and rates2.length == pairs2.length
- 1 ≤ pairs1[i][0].length, pairs1[i][1].length ≤ 5
- 0.01 ≤ rates1[i], rates2[i] ≤ 100
- All currency names consist of uppercase English letters only
- No contradictory rates within the same day
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code