Minimum Fuel Cost to Report to the Capital - Problem

There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of n cities numbered from 0 to n - 1 and exactly n - 1 roads. The capital city is city 0.

You are given a 2D integer array roads where roads[i] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.

There is a meeting for the representatives of each city. The meeting is in the capital city.

There is a car in each city. You are given an integer seats that indicates the number of seats in each car.

A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.

Return the minimum number of liters of fuel to reach the capital city.

Input & Output

Example 1 — Basic Tree
$ Input: roads = [[0,1],[0,2],[0,3]], seats = 5
Output: 3
💡 Note: Capital 0 connects to cities 1, 2, 3. Each city sends 1 representative, each needs 1 car (since 1 ≤ 5 seats). Total: 1 + 1 + 1 = 3 liters.
Example 2 — Limited Seats
$ Input: roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2
Output: 7
💡 Note: Tree structure requires multiple cars due to seat limitation. Representatives share rides optimally based on subtree sizes and seat capacity.
Example 3 — Single Road
$ Input: roads = [[0,1]], seats = 1
Output: 1
💡 Note: Only city 1 needs to send representative to capital 0. One car travels the single road: 1 liter.

Constraints

  • 1 ≤ n ≤ 105
  • roads.length == n - 1
  • roads[i].length == 2
  • 0 ≤ ai, bi < n
  • ai ≠ bi
  • roads represents a valid tree
  • 1 ≤ seats ≤ 105

Visualization

Tap to expand
Minimum Fuel Cost: Representatives Travel to CapitalInput:0123seats = 5Process:0123Each needs 1 carOutput:3 litersTotal fuel costCapitalCapital🎯 Key Insight: Share rides optimally based on subtree sizes and car capacity
Understanding the Visualization
1
Input
Tree structure with roads connecting cities, capital at city 0
2
Process
Calculate minimum cars needed for ride sharing to capital
3
Output
Total liters of fuel (one per car journey between cities)
Key Takeaway
🎯 Key Insight: Use DFS to count people in each subtree and calculate minimum cars needed per edge
Asked in
Google 25 Amazon 20 Microsoft 15
35.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen