#1928

Minimum Cost to Reach Destination in Time

Hard
ArrayDynamic ProgrammingGraph TheoryGraph TraversalPriority QueueDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(E log V)
Space
O(1)
O(V)
💡

Intuition

Time O(E log V)Space O(V)

The optimal approach uses a modified Dijkstra's algorithm to efficiently find the minimum cost path while considering both travel time and passing fees. This method leverages a priority queue to explore the most promising paths first, ensuring we find the minimum cost without exhaustively searching every path.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a graph representation from the edges.
  2. 2Step 2: Use a priority queue to explore paths, storing the current city, total time, and total cost.
  3. 3Step 3: For each city, if the current time is within maxTime, update the cost and explore neighboring cities.
  4. 4Step 4: Continue until reaching city n-1 or exhausting all options, returning the minimum cost found.
solution.py24 lines
1import heapq
2from collections import defaultdict
3
4def minCost(maxTime, edges, passingFees):
5    graph = defaultdict(list)
6    for x, y, time in edges:
7        graph[x].append((y, time))
8        graph[y].append((x, time))
9
10    pq = [(passingFees[0], 0, 0)]  # (cost, time, city)
11    min_cost = {(0, 0): passingFees[0]}
12
13    while pq:
14        cost, time, city = heapq.heappop(pq)
15        if city == len(passingFees) - 1:
16            return cost
17        for neighbor, travel_time in graph[city]:
18            new_time = time + travel_time
19            new_cost = cost + passingFees[neighbor]
20            if new_time <= maxTime:
21                if (neighbor, new_time) not in min_cost or new_cost < min_cost[(neighbor, new_time)]:
22                    min_cost[(neighbor, new_time)] = new_cost
23                    heapq.heappush(pq, (new_cost, new_time, neighbor))
24    return -1

Complexity note: The time complexity is O(E log V) due to the priority queue operations, where E is the number of edges and V is the number of vertices (cities). The space complexity is O(V) for storing the graph and the minimum costs.

  • 1Using a priority queue allows us to efficiently explore the most promising paths first.
  • 2Combining travel time and passing fees into a single cost metric helps streamline the search process.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.