#2065

Maximum Path Quality of a Graph

Hard
ArrayBacktrackingGraph TheoryBacktrackingGraph Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n^2)
Space
O(n)
O(n)
💡

Intuition

Time O(n^2)Space O(n)

The optimal solution uses a backtracking approach with pruning to explore paths efficiently. By keeping track of the total time and unique nodes visited, we can avoid unnecessary paths and focus on those that maximize quality within the time limit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Build the graph representation from the edges.
  2. 2Step 2: Use a backtracking function that explores paths recursively, keeping track of the current time and unique nodes visited.
  3. 3Step 3: If the current path returns to node 0 and the time is within limits, calculate the quality and update the maximum quality.
solution.py20 lines
1def maxPathQuality(values, edges, maxTime):
2    from collections import defaultdict
3    graph = defaultdict(list)
4    for u, v, t in edges:
5        graph[u].append((v, t))
6        graph[v].append((u, t))
7
8    def dfs(node, timeSpent, visited):
9        if timeSpent > maxTime:
10            return 0
11        if node == 0:
12            return sum(values[i] for i in visited)
13        maxQuality = 0
14        for neighbor, travelTime in graph[node]:
15            visited.add(neighbor)
16            maxQuality = max(maxQuality, dfs(neighbor, timeSpent + travelTime, visited))
17            visited.remove(neighbor)
18        return maxQuality
19
20    return dfs(0, 0, {0})

Complexity note: The time complexity is quadratic due to the backtracking approach that explores paths while keeping track of visited nodes. The space complexity is linear due to the storage of the graph and visited nodes.

  • 1Exploring all paths can lead to exponential time complexity.
  • 2Using backtracking with pruning can significantly reduce unnecessary computations.

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