There are n cities connected by some number of flights. You are given an array flights where flights[i] = [from_i, to_i, price_i] indicates that there is a flight from city from_i to city to_i with cost price_i.

You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
💡 Note: The optimal path is 0→1→3 with cost 100+600=700. We can't use 0→2→3 (cost 300) because it requires 2 stops but k=1.
Example 2 — No Valid Path
$ Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
💡 Note: With k=0 (direct flight only), we must take the direct route 0→2 with cost 500. Path 0→1→2 requires 1 stop which exceeds k=0.
Example 3 — Multiple Options
$ Input: n = 4, flights = [[0,1,1],[0,2,5],[1,2,1],[2,3,1]], src = 0, dst = 3, k = 1
Output: 6
💡 Note: Best path with at most 1 stop is 0→2→3 with cost 5+1=6. Path 0→1→2→3 would cost only 3 but requires 2 stops.

Constraints

  • 1 ≤ n ≤ 100
  • 0 ≤ flights.length ≤ (n × (n - 1) / 2)
  • flights[i].length == 3
  • 0 ≤ fromi, toi < n
  • fromi ≠ toi
  • 1 ≤ pricei ≤ 104
  • There will not be any multiple flights between two cities.
  • 0 ≤ src, dst, k < n
  • src ≠ dst

Visualization

Tap to expand
INPUTALGORITHMRESULT0123100500600200Flight Networksrc = 0, dst = 3, k = 1At most 1 stop allowed1Initialize DP tabledp[stops][city] = min cost2Relax all edgesFor each stop count3Update minimum costsTrack best path to each city4Return resultdp[k+1][dst] or -1013100600Optimal Path FoundPath: 0 → 1 → 3Cost: 100 + 600 = 700700Minimum CostKey Insight:Dynamic programming tracks minimum cost to reach each city with exactly i stops, ensuring optimal substructureTutorialsPoint - Cheapest Flights Within K Stops | Dynamic Programming
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
89.0K Views
Medium Frequency
~35 min Avg. Time
3.5K 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