We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Cost of Trip With K Highways

Number: 2007

Difficulty: Hard

Paid? Yes

Companies: N/A


Problem Description

There are n cities connected by highways. Each highway connects two different cities bidirectionally and has an associated toll cost. Given a list of highways, you need to plan a trip that uses exactly k highways. You may start at any city, and you cannot visit the same city twice. The goal is to find the maximum possible total toll cost over all valid trips that use exactly k highways. If there is no valid trip, return -1.


Key Insights

  • The graph is undirected and each edge (highway) can be used only once, since cities cannot be revisited.
  • Since k must be exactly met and no city is allowed to be repeated, the maximum highways in any valid simple path is bounded by n - 1. Thus if k > n - 1, the answer is immediately -1.
  • Use Depth-First Search (DFS) with memoization (bitmask DP) because n is small (n ≤ 15). The state can be characterized by (current city, visited cities bitmask, highways used so far).
  • We need to maximize the accumulated toll cost over exactly k edges.

Space and Time Complexity

Time Complexity: O(n * 2^n * k) in the worst case, where n ≤ 15.
Space Complexity: O(n * 2^n * k) for the memoization cache.


Solution

We can solve the problem using DFS with memoization.

  1. First, build an adjacency list from the highway list.
  2. Check whether k > n - 1; if so, return -1 immediately because a simple path cannot have that many edges.
  3. Define a DFS function that takes the current city, a bitmask of visited cities, and the number of highways used so far, and returns the maximum extra toll that can be collected from that state if completing a trip with exactly k highways.
  4. In the DFS, if the count of highways used equals k, return 0 (base case). Otherwise, iterate through neighbors in the adjacency list. For any neighbor that has not been visited, try taking that highway and recursively solving for the new state.
  5. Save the computed results for each state (city, mask, count) in a cache to avoid recomputation.
  6. Finally, run the DFS from every city as a starting point and return the maximum cost, or -1 if no valid trip exists.

Code Solutions

Below are the implementations in Python, JavaScript, C++, and Java with line-by-line comments.

# Build the solution using DFS with memoization and bitmask DP.
def maximumCostTrip(n, highways, k):
    # If k exceeds the number of highways available in any simple path
    if k > n - 1:
        return -1

    from collections import defaultdict
    graph = defaultdict(list)
    # Build the adjacency list for undirected graph
    for u, v, toll in highways:
        graph[u].append((v, toll))
        graph[v].append((u, toll))

    # memo dictionary to store computed states: (current, mask, count) -> max toll
    memo = {}

    # DFS function returning maximum extra cost from this state to complete a valid trip
    def dfs(current, mask, count):
        # Base case: reached exactly k highways, so no additional toll.
        if count == k:
            return 0
        # Memoization check
        key = (current, mask, count)
        if key in memo:
            return memo[key]
        max_toll = float('-inf')
        # Explore each neighbor that has not been visited
        for neighbor, toll in graph[current]:
            # Check if neighbor was already visited using bitmask
            if mask & (1 << neighbor):
                continue
            # Explore further by taking the current highway
            new_mask = mask | (1 << neighbor)
            next_toll = dfs(neighbor, new_mask, count + 1)
            if next_toll != float('-inf'):
                max_toll = max(max_toll, toll + next_toll)
        memo[key] = max_toll
        return max_toll

    overall_max = float('-inf')
    # Try starting from every city
    for city in range(n):
        overall_max = max(overall_max, dfs(city, 1 << city, 0))
    return overall_max if overall_max != float('-inf') else -1

# Example usage:
#print(maximumCostTrip(5, [[0,1,4],[2,1,3],[1,4,11],[3,2,3],[3,4,2]], 3))
← Back to All Questions