Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Maximize Amount After Two Days of Conversions

Updated
5 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3387" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given a string initialCurrency, and you start with 1.0 of initialCurrency. You are also given four arrays with currency pairs (strings) and rates (real numbers): pairs1[i] = [startCurrencyi, targetCurrencyi] denotes that you can convert from startCurrencyi to targetCurrencyi at a rate of rates1[i] on day 1. pairs2[i] = [startCurrencyi, targetCurrencyi] denotes that you can convert from startCurrencyi to targetCurrencyi at a rate of rates2[i] on day 2. Also, each targetCurrency can be converted back to its corresponding startCurrency at a rate of 1 / rate. You can perform any number of conversions, including zero, using rates1 on day 1, followed by any number of additional conversions, including zero, using rates2 on day 2. Return the maximum amount of initialCurrency you can have after performing any number of conversions on both days in order. Note: Conversion rates are valid, and there will be no contradictions in the rates for either day. The rates for the days are independent of each other. Example 1: Input: initialCurrency = "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.00000 Explanation: To get the maximum amount of EUR, starting with 1.0 EUR: On Day 1: Convert EUR to USD to get 2.0 USD. Convert USD to JPY to get 6.0 JPY. On Day 2: Convert JPY to USD to get 24.0 USD. Convert USD to CHF to get 120.0 CHF. Finally, convert CHF to EUR to get 720.0 EUR. Example 2: Input: initialCurrency = "NGN", pairs1 = [["NGN","EUR"]], rates1 = [9.0], pairs2 = [["NGN","EUR"]], rates2 = [6.0] Output: 1.50000 Explanation: Converting NGN to EUR on day 1 and EUR to NGN using the inverse rate on day 2 gives the maximum amount. Example 3: Input: initialCurrency = "USD", pairs1 = [["USD","EUR"]], rates1 = [1.0], pairs2 = [["EUR","JPY"]], rates2 = [10.0] Output: 1.00000 Explanation: In this example, there is no need to make any conversions on either day. Constraints: 1 <= initialCurrency.length <= 3 initialCurrency consists only of uppercase English letters. 1 <= n == pairs1.length <= 10 1 <= m == pairs2.length <= 10 pairs1[i] == [startCurrencyi, targetCurrencyi] pairs2[i] == [startCurrencyi, targetCurrencyi] 1 <= startCurrencyi.length, targetCurrencyi.length <= 3 startCurrencyi and targetCurrencyi consist only of uppercase English letters. rates1.length == n rates2.length == m 1.0 <= rates1[i], rates2[i] <= 10.0 The input is generated such that there are no contradictions or cycles in the conversion graphs for either day. The input is generated such that the output is at most 5 * 1010.

Explanation

Here's a breakdown of the solution:

  • Graph Representation: Model each day's currency conversions as a directed graph where nodes are currencies and edges represent conversion rates. Include reverse rates for converting back.
  • Bellman-Ford Algorithm: Apply the Bellman-Ford algorithm to find the maximum possible value for each currency reachable from the initial currency on each day. Bellman-Ford handles potentially beneficial cycles, unlike Dijkstra's algorithm.
  • Two-Day Optimization: Run Bellman-Ford for Day 1. Then, using the results from Day 1 as the starting values, run Bellman-Ford again for Day 2 to determine the final maximum amount.

  • Runtime Complexity: O((n + m) * V * E), where n and m are the number of pairs in pairs1 and pairs2 respectively, V is the number of vertices (currencies), and E is the number of edges (conversions) in the graphs. Since V and E are relatively small and bounded by constants, this is effectively O(n + m). Storage Complexity: O(V + E) to store the graphs and distances.

Code

    def solve():
    initialCurrency = input()
    pairs1_str = input()
    rates1_str = input()
    pairs2_str = input()
    rates2_str = input()

    pairs1 = eval(pairs1_str)
    rates1 = eval(rates1_str)
    pairs2 = eval(pairs2_str)
    rates2 = eval(rates2_str)

    def bellman_ford(initial_currency, pairs, rates):
        graph = {}
        currencies = set([initial_currency])
        for pair in pairs:
            currencies.add(pair[0])
            currencies.add(pair[1])
        currencies = list(currencies)

        for currency in currencies:
            graph[currency] = {}

        for i, pair in enumerate(pairs):
            start_currency = pair[0]
            target_currency = pair[1]
            rate = rates[i]
            graph[start_currency][target_currency] = rate
            graph[target_currency][start_currency] = 1 / rate

        distances = {currency: 0.0 for currency in currencies}
        distances[initial_currency] = 1.0

        for _ in range(len(currencies) - 1):
            for start_currency in currencies:
                for target_currency, rate in graph[start_currency].items():
                    if distances[start_currency] > 0 and distances[start_currency] * rate > distances[target_currency]:
                        distances[target_currency] = distances[start_currency] * rate

        return distances

    # Day 1
    day1_distances = bellman_ford(initialCurrency, pairs1, rates1)

    # Day 2
    pairs2_with_modified_start = []
    rates2_modified = []

    currencies_day2 = set()
    for pair in pairs2:
        currencies_day2.add(pair[0])
        currencies_day2.add(pair[1])


    initial_values = {}
    for currency in currencies_day2:
        initial_values[currency] = 0.0
        if currency in day1_distances:
             initial_values[currency] = day1_distances[currency]


    for i, pair in enumerate(pairs2):
        pairs2_with_modified_start.append(pair)
        rates2_modified.append(rates2[i])

    modified_pairs = []
    modified_rates = []

    for i in range(len(pairs2)):
        modified_pairs.append(pairs2[i])
        modified_rates.append(rates2[i])

    def bellman_ford_modified(initial_values, pairs, rates):
        graph = {}
        currencies = set(initial_values.keys())
        currencies = list(currencies)

        for currency in currencies:
            graph[currency] = {}

        for i, pair in enumerate(pairs):
            start_currency = pair[0]
            target_currency = pair[1]
            rate = rates[i]
            graph[start_currency][target_currency] = rate
            graph[target_currency][start_currency] = 1 / rate

        distances = initial_values.copy()


        for _ in range(len(currencies) - 1):
            for start_currency in currencies:
                if start_currency not in graph:
                  continue
                for target_currency, rate in graph[start_currency].items():
                    if distances[start_currency] > 0 and distances[start_currency] * rate > distances[target_currency]:
                        distances[target_currency] = distances[start_currency] * rate

        return distances

    day2_distances = bellman_ford_modified(initial_values, modified_pairs, modified_rates)

    max_amount = 0.0
    for currency, amount in day2_distances.items():
        max_amount = max(max_amount, amount)

    print(f"{max_amount:.5f}")

solve()

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Maximize Amount After Two Days of Conversions