#2646

Minimize the Total Price of the Trips

Hard
ArrayDynamic ProgrammingTreeDepth-First SearchGraph TheoryGraph TraversalDepth-First SearchDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal approach uses Depth-First Search (DFS) to calculate the frequency of each node's price being used in the trips, allowing us to halve the prices of non-adjacent nodes strategically to minimize the total cost.

⚙️

Algorithm

4 steps
  1. 1Step 1: Build the graph from the edges.
  2. 2Step 2: Use DFS to calculate the frequency of each node being visited across all trips.
  3. 3Step 3: Determine which nodes to halve based on their frequency and adjacency constraints.
  4. 4Step 4: Calculate the total price using the modified prices.
solution.py19 lines
1def dfs(node, graph, visited, freq):
2    visited.add(node)
3    for neighbor in graph[node]:
4        if neighbor not in visited:
5            freq[neighbor] += 1
6            dfs(neighbor, graph, visited, freq)
7
8def total_price(n, edges, price, trips):
9    graph = {i: [] for i in range(n)}
10    for a, b in edges:
11        graph[a].append(b)
12        graph[b].append(a)
13    freq = [0] * n
14    for start, end in trips:
15        visited = set()
16        dfs(start, graph, visited, freq)
17        freq[end] += 1
18    total = sum(freq[i] * price[i] for i in range(n))
19    return total

Complexity note: This complexity arises from traversing the tree once to build the graph and once for each trip to calculate frequencies, leading to O(n + m) where m is the number of trips.

  • 1Understanding tree traversal is crucial for calculating paths.
  • 2Frequency counting helps optimize the price calculation.

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