Problem Description
You are given an initial currency and start with 1.0 unit of it. There are two sets of conversion rules provided as currency pairs with associated rates – one set for day 1 and one set for day 2. For each conversion given (from A to B with rate r), the reverse conversion (from B back to A) is also allowed at rate 1/r. On day 1, you can perform any number of conversions using the first set, and then on day 2, any sequence of conversions using the second set. The task is to determine the maximum amount of the initial currency you can end up with after applying conversions on day 1 followed by day 2.
Key Insights
- Both day1 and day2 conversion rules form a bidirectional graph, where each edge is available in both directions (with the inverse rate used for the reverse conversion).
- The problem can be separated into two independent stages: • Compute the maximum conversion multiplier from the initial currency to every other currency on day 1. • Compute the maximum conversion multiplier from any currency back to the initial currency on day 2.
- Using a relaxation algorithm (similar to Bellman–Ford for maximum products) works because the graphs are small and there are no arbitrage cycles that allow infinite profit.
- Finally, the answer is the maximum product over all intermediate currencies v, where the overall multiplier is the product from day1 (S→v) and day2 (v→S).
Space and Time Complexity
Time Complexity: O(V * E) per day where V is the number of currencies and E is the number of conversion pairs (including both directions); given the constraints, V and E are very small. Space Complexity: O(V + E) for storing the graph and the multiplier arrays.
Solution
We first build the conversion graph for day 1 using the provided currency pairs and their inverses. We then use a relaxation algorithm to compute the highest conversion factor from the initial currency to every other currency. For day 2, our goal is to compute the maximum conversion factor from any currency back to the initial currency. To do this efficiently, we reverse the direction of edges (which effectively computes the maximum multiplier from the currency to the initial) and again use the relaxation algorithm starting from the initial currency. Finally, we iterate through all currencies and compute the product of the maximum multiplier from day 1 (S to v) and day 2 (v to S), and return the maximum product.
The key trick is that by decomposing the problem into two separate maximization steps, we can easily combine the best conversion multiplier from day 1 with the best "reverse" conversion multiplier from day 2 for each currency. Since the conversion graphs are bidirectional with known inverse rates, the relaxation approach (over at most |V| - 1 iterations) suffices to compute the optimal conversion factors.