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 Trip: Find Best Path Using Exactly K=2 HighwaysInput: Highway Network012315810205Process: Try All Paths (k=2)Path Options:0→1→2: 15+10 = 250→1→3: 15+20 = 35 ✓0→3→2: 8+5 = 131→2→3: 10+5 = 151→3→2: 20+5 = 25...and moreOutput: Maximum Cost35Best Path:0 → 1 → 3Constraint: Use exactly k=2 highways, visit each city at most onceAlgorithm: DFS + Memoization with bitmask for visited citiesTime Complexity: O(n × 2ⁿ × k) | Space Complexity: O(n × 2ⁿ × k)
Understanding the Visualization
1
Input Graph
Cities connected by highways with toll costs
2
Path Finding
Find paths using exactly k highways without revisiting cities
3
Maximum Cost
Return the highest total cost among all valid paths
Key Takeaway
🎯 Key Insight: Use bitmasks to efficiently represent visited city states and memoization to avoid redundant computations
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