#3387
Maximize Amount After Two Days of Conversions
MediumArrayStringDepth-First SearchBreadth-First SearchGraph TheoryHash MapGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages a graph-like approach to find the best conversion rates. We can use a dictionary to store the maximum conversion rates for each currency, allowing us to efficiently compute the best conversions in linear time.
⚙️
Algorithm
3 steps- 1Step 1: Create a mapping of conversion rates for day 1 and day 2 using dictionaries.
- 2Step 2: For each currency in the day 1 mapping, calculate the maximum amount obtainable after day 2 conversions.
- 3Step 3: Return the maximum amount found.
solution.py17 lines
1def maxAmount(initialCurrency, pairs1, rates1, pairs2, rates2):
2 from collections import defaultdict
3 rates_day1 = defaultdict(float)
4 rates_day2 = defaultdict(float)
5 for i in range(len(pairs1)):
6 rates_day1[pairs1[i][0]] = max(rates_day1[pairs1[i][0]], rates1[i])
7 for i in range(len(pairs2)):
8 rates_day2[pairs2[i][0]] = max(rates_day2[pairs2[i][0]], rates2[i])
9 max_amount = 1.0
10 for currency in rates_day1:
11 if currency == initialCurrency:
12 continue
13 amount_day1 = 1.0 * rates_day1[currency]
14 if currency in rates_day2:
15 amount_day2 = amount_day1 * rates_day2[currency]
16 max_amount = max(max_amount, amount_day2)
17 return max_amountℹ
Complexity note: The complexity is linear because we are only iterating through the pairs once to build the conversion maps.
- 1Understanding currency conversion as a graph problem helps in visualizing the relationships between currencies.
- 2Using dictionaries to store maximum rates allows for efficient lookups and calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.