Loading
Loading
A budget travel site knows n airports numbered 0 to n − 1 and a list of one-way flights, each [from, to, price].
A traveller wants to get from origin to destination but will accept at most maxStops layovers — intermediate airports between the two. Return the cheapest total price, or -1 if no route respects the limit.
n = 4, flights = [[0,1,100],[1,2,100],[0,2,500],[1,3,600],[2,3,200]], origin = 0, destination = 3, maxStops = 10 → 1 → 3one layover, 100 + 600 = 7000 → 2 → 3one layover, 500 + 200 = 7000 → 1 → 2 → 3only 400, but needs two layovers700Sign in to keep a note here. It is free, and nobody else can see it.
Sign inExample 1
| 0 | 0 | 1 | 100 |
|---|---|---|---|
| 1 | 1 | 2 | 100 |
| 2 | 0 | 2 | 500 |
| 3 | 1 | 3 | 600 |
| 4 | 2 | 3 | 200 |
Sign in to open hints.
Struggling is where the learning happens. Open this once you have genuinely tried, or once the hints have run out.
O(k × flights) time · O(n) space
Input. Run your code to watch it work on this input, one line at a time.
| 0 | 0 | 1 | 100 |
|---|---|---|---|
| 1 | 1 | 2 | 100 |
| 2 | 0 | 2 | 500 |
| 3 | 1 | 3 | 600 |
| 4 | 2 | 3 | 200 |
Running code is turned off on this deployment. You can still read the problem, write code, use hints and the visualizer.
Tab moves focus out of the editor. Press Ctrl+M to let Tab indent instead.
No results yet
Run your code against the sample tests, or submit to run the full suite.
Example 2
| 0 | 0 | 1 | 100 |
|---|---|---|---|
| 1 | 1 | 2 | 100 |
| 2 | 0 | 2 | 500 |
| 3 | 1 | 3 | 600 |
| 4 | 2 | 3 | 200 |
Example 3
| 0 | 0 | 1 | 50 |
|---|---|---|---|
| 1 | 1 | 2 | 50 |
With no layovers allowed only a direct flight would do, and there is none.