Maximum Cost of Trip With K Highways - Problem

A series of highways connect n cities numbered from 0 to n - 1. You are given a 2D integer array highways where highways[i] = [city1i, city2i, tolli] indicates that there is a highway that connects city1i and city2i, allowing a car to go from city1i to city2i and vice versa for a cost of tolli.

You are also given an integer k. You are going on a trip that crosses exactly k highways. You may start at any city, but you may only visit each city at most once during your trip.

Return the maximum cost of your trip. If there is no trip that meets the requirements, return -1.

Input & Output

Example 1 — Basic Case
$ Input: highways = [[0,1,15],[0,3,8],[1,2,10],[1,3,20],[2,3,5]], k = 2
Output: 35
💡 Note: Start at city 0, take highway to city 1 (cost 15), then take highway to city 3 (cost 20). Total cost = 15 + 20 = 35, using exactly 2 highways.
Example 2 — No Valid Path
$ Input: highways = [[0,1,10],[1,2,5]], k = 3
Output: -1
💡 Note: Only 3 cities connected in a line, but we need exactly 3 highways. Maximum possible is 2 highways (0→1→2), so return -1.
Example 3 — Single Highway
$ Input: highways = [[0,1,100]], k = 1
Output: 100
💡 Note: Only one highway available with cost 100. We need exactly 1 highway, so the answer is 100.

Constraints

  • 1 ≤ highways.length ≤ 15
  • highways[i].length == 3
  • 0 ≤ city1i, city2i ≤ n - 1
  • city1i ≠ city2i
  • 0 ≤ tolli ≤ 100
  • 1 ≤ k ≤ 50
  • There are no duplicate highways.

Visualization

Tap to expand
Maximum Cost of Trip With K Highways INPUT Graph with 4 cities (nodes 0-3) 0 1 2 3 15 8 10 20 5 highways = [[0,1,15],[0,3,8], [1,2,10],[1,3,20],[2,3,5]] k = 2 Find path crossing exactly k=2 highways with max cost (visit each city at most once) ALGORITHM (DFS) 1 Build Adjacency List Store edges with costs for each node 2 Start DFS from Each City Try all possible starting points (0, 1, 2, 3) 3 Explore All Paths Use visited mask, track cost, stop at k highways 4 Track Maximum Cost Update max when k highways crossed DFS Exploration Example Path 0-->1-->3: 15+20=35 Path 0-->1-->2: 15+10=25 Path 0-->3-->1: 8+20=28 Path 1-->3-->0: 20+8=28 ... Best: 0-->1-->3 = 35 FINAL RESULT Optimal Path Found 0 1 3 15 20 Maximum Cost 35 Calculation: 15 + 20 = 35 OK - 2 highways crossed Key Insight: DFS with backtracking explores all possible paths of exactly k highways. Use a bitmask to track visited cities efficiently. The constraint that each city can be visited at most once prevents cycles and ensures we find simple paths. Time complexity: O(n! / (n-k-1)!) for exploring all valid paths of length k. TutorialsPoint - Maximum Cost of Trip With K Highways | DFS Approach
Asked in
Google 12 Amazon 8 Microsoft 6 Meta 4
8.5K Views
Medium Frequency
~35 min Avg. Time
245 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